在 Visual Basic 中,属性(Property)可以通过两种方式声明:
' 自动属性 Public Property Name As String ' 完全属性 Private _age As Integer Public Property Age As Integer Get Return _age End Get Set(value As Integer) If value < 0 Then Throw New ArgumentException("年龄不能为负") _age = value End Set End Property
使用 Set 的细节:
Value 是一个伪变量,引用被赋值的值。Set 内可以执行验证、记录、触发事件。何时使用:
在 VB.NET 中将
Set(ByVal value As Integer)写成Set(value As Integer)有何后果?为什么不应该这样写?
回答:
VB.NET 的语法不需要(也不支持)在 Set 中明确声明参数 ByVal — 只需使用 Set(value As Type)。如果写成 Set(ByVal value As Integer),将导致编译错误。
错误代码示例:
'Set(ByVal value As Integer) — 编译错误 Public Property Prop As Integer Set(ByVal value As Integer) ... End Set End Property
在经典的 VB6 中,这种语法是允许的,但在 VB.NET 中严格要求 Set(value As Type)。
历史
ByVal — 编译器产生了神秘的错误,开发人员长期无法定位,因为 lint 工具没有明确指出原因。历史
历史
在通过自动属性复制引用类型的对象时,忘记通过 Get/Set 实现深拷贝。结果会导致对同一对象的引用重复;一个实例的更改会导致另一个实例的更改。