vb.net 具有公共 getter 和私有 setter 的自动属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14085180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto Property with public getter and private setter
提问by Tilak
NOTE:This is not a duplicateof VB.NET equivalent of C# property shorthand?. Thisquestion is about how to have different access rightson getter and setter of a VB auto-property; e.g public getter and private setter. Thatquestion is about the syntax for auto-property (and does not mention this issue).
注意:这不是C# 属性速记的VB.NET 等价物的副本吗?. 这个问题是关于如何对VB自动属性的getter和setter拥有不同的访问权限;例如公共 getter 和私有 setter。这个问题是关于自动属性的语法(并且没有提到这个问题)。
I am trying to convert an auto Property (publicgetter and privatesetter) from C# to VB.NET.
我正在尝试将自动属性(公共getter 和私有setter)从 C# 转换为 VB.NET。
But after conversion VB.NET is maintaining a private field.
但是在转换后 VB.NET 维护了一个私有字段。
C# code
C#代码
class DemoViewModel
{
DemoViewModel (){ AddCommand = new RelayCommand(); }
public ICommand AddCommand {get;private set;}
}
VB.NET equivalent from code converteris
来自代码转换器的VB.NET 等效项是
Class DemoViewModel
Private Sub New()
AddCommand = New RelayCommand()
End Sub
Public Property AddCommand() As ICommand
Get
Return m_AddCommand
End Get
Private Set
m_AddCommand = Value
End Set
End Property
Private m_AddCommand As ICommand
End Class
VB.NET code generates private backing field.
VB.NET 代码生成私有支持字段。
Is it possible to get rid of this back field in source code (like c#)? How?
是否可以在源代码(如 c#)中去掉这个 back 字段?如何?
Without this feature, VB.NET source will have lots of such redundancy.
如果没有这个特性,VB.NET 源码就会有很多这样的冗余。
回答by SergeyS
Using VB.NET, if you want to specify different accessibilityfor the Get and Set procedure, then you cannot use an auto-implemented propertyand must instead use standard, or expanded, property syntax.
使用 VB.NET,如果要为 Get 和 Set 过程指定不同的可访问性,则不能使用自动实现的属性,而必须使用标准或扩展的属性语法。
Read MSDN: http://msdn.microsoft.com/en-us/library/dd293589.aspx
阅读 MSDN:http: //msdn.microsoft.com/en-us/library/dd293589.aspx
If getter and setter have same accessibility, e.g. both are Public, then you can use the auto-property syntax, e.g.:
如果 getter 和 setter具有相同的可访问性,例如两者都是Public,那么您可以使用自动属性语法,例如:
Public Property Prop2 As String = "Empty"
回答by p3tch
In VB.NET it's
在 VB.NET 中它是
Public ReadOnly Property Value As String
Then to access the private setter, you use an underscore before your property name
然后要访问私有 setter,请在属性名称前使用下划线
Me._Value = "Fred"
回答by dba
since the answer(s) above hold(s), you may introduce a Public Prop to expose the Private one. This may not be a nice solution but still less code, than expanded Property syntax
由于上述答案成立,您可以引入一个公共道具来公开私人道具。这可能不是一个很好的解决方案,但与扩展的 Property 语法相比,代码仍然更少
Private Property internalprop as object
Public Readonly Property exposedprop as Object = internalprop

