具有公共 getter 和私有 setter 的自动属性 [英] Auto Property with public getter and private setter
问题描述
注意:这不是VB.NET 等效于 C# 属性简写?.这个问题是关于如何对VB自动属性的getter和setter拥有不同的访问权限;例如公共 getter 和私有 setter.那个问题是关于自动属性的语法(并没有提到这个问题).
NOTE: This is not a duplicate of VB.NET equivalent of C# property shorthand?. This question is about how to have different access rights on getter and setter of a VB auto-property; e.g public getter and private setter. That question is about the syntax for auto-property (and does not mention this issue).
我正在尝试将自动属性(public getter 和 private setter)从 C# 转换为 VB.NET.
I am trying to convert an auto Property (public getter and private setter) from C# to VB.NET.
但转换后 VB.NET 维护一个私有字段.
But after conversion VB.NET is maintaining a private field.
C# 代码
class DemoViewModel
{
DemoViewModel (){ AddCommand = new RelayCommand(); }
public ICommand AddCommand {get;private set;}
}
VB.NET 等效于 代码转换器是
VB.NET equivalent from code converter is
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 代码生成私有支持字段.
VB.NET code generates private backing field.
是否可以在源代码(如 c#)中去掉这个 back 字段?怎么样?
Is it possible to get rid of this back field in source code (like c#)? How?
如果没有这个特性,VB.NET 源码就会有很多这样的冗余.
Without this feature, VB.NET source will have lots of such redundancy.
推荐答案
使用 VB.NET,如果您希望为 Get 和 Set 过程指定不同的可访问性,则您不能使用自动实现的属性,并且必须使用标准或扩展的属性语法.
Using VB.NET, if you want to specify different accessibility for the Get and Set procedure, then you cannot use an auto-implemented property and must instead use standard, or expanded, property syntax.
如果 getter 和 setter 具有相同的可访问性,例如两者都是Public
,那么你可以使用自动属性语法,例如:
If getter and setter have same accessibility, e.g. both are Public
, then you can use the auto-property syntax, e.g.:
Public Property Prop2 As String = "Empty"
这篇关于具有公共 getter 和私有 setter 的自动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!