Class VB.NET 中的字段可以不使用 Getter & Setter?
Class Fields in VB.NET can be encapsulated without the Getter & Setter?
在 VB.NET 中,我注意到我可以通过使用 属性 关键字后跟 属性 名称和数据类型直接创建 属性需要 getter 和 setter 方法,而我不能在 C# 中执行此操作!
尽管如此,这个属性似乎被封装了,就好像我把它放在了getter和setter方法中一样!
请看下面的截图。
在上面的截图中,我说的 属性 是 number1,我创建了另一个 属性 封装在 getter 和 setter 方法调用了 number2.
然后,我在 Class2 中创建了 Class1 的新实例,但我注意到 number1 属性 直到我才公开已经创建了它的 class 的一个实例,就像它被封装在 getter 和 setter 方法中一样,例如 number2 属性!
有什么解释吗?
这称为 "auto property",在 VB.NET documentation:
中定义得非常清楚
Public Property Name As String
Public Property Owner As String = "DefaultName"
Public Property Items As New List(Of String) From {"M", "T", "W"}
Public Property ID As New Guid()
都是具有 getter 和 setter(以及自动创建的支持字段)的自动属性。
C# 要求您使用 {get; set;}
但基本相同(因为 C# 没有 Property
关键字,它需要一些东西来区分字段和 属性,所以 {get; set;}
就是这样做的)。 C# 有点不同,因为您可以定义 getter-only 属性而无需 {get; set;}
...
public int MyProperty => 10;
相当于
public int MyProperty { get { return 10; } }
but I've noticed that the number1 property isn't exposed until I've
created an instance of its class which is the same as if it was
encapsulated in a getter and setter method like the number2 property!
在创建 class 的实例之前不会公开任何内容(不是方法、字段或属性)!这与 getter/ setter 或 属性 无关...只是您的基本 OOP
唯一的例外是 methods/fields/properties 和 "shared" 关键字("static" 在 c# 中)
在 VB.NET 中,我注意到我可以通过使用 属性 关键字后跟 属性 名称和数据类型直接创建 属性需要 getter 和 setter 方法,而我不能在 C# 中执行此操作!
尽管如此,这个属性似乎被封装了,就好像我把它放在了getter和setter方法中一样!
请看下面的截图。
在上面的截图中,我说的 属性 是 number1,我创建了另一个 属性 封装在 getter 和 setter 方法调用了 number2.
然后,我在 Class2 中创建了 Class1 的新实例,但我注意到 number1 属性 直到我才公开已经创建了它的 class 的一个实例,就像它被封装在 getter 和 setter 方法中一样,例如 number2 属性!
有什么解释吗?
这称为 "auto property",在 VB.NET documentation:
中定义得非常清楚Public Property Name As String
Public Property Owner As String = "DefaultName"
Public Property Items As New List(Of String) From {"M", "T", "W"}
Public Property ID As New Guid()
都是具有 getter 和 setter(以及自动创建的支持字段)的自动属性。
C# 要求您使用 {get; set;}
但基本相同(因为 C# 没有 Property
关键字,它需要一些东西来区分字段和 属性,所以 {get; set;}
就是这样做的)。 C# 有点不同,因为您可以定义 getter-only 属性而无需 {get; set;}
...
public int MyProperty => 10;
相当于
public int MyProperty { get { return 10; } }
but I've noticed that the number1 property isn't exposed until I've created an instance of its class which is the same as if it was encapsulated in a getter and setter method like the number2 property!
在创建 class 的实例之前不会公开任何内容(不是方法、字段或属性)!这与 getter/ setter 或 属性 无关...只是您的基本 OOP
唯一的例外是 methods/fields/properties 和 "shared" 关键字("static" 在 c# 中)