Greetins,
我只是一段时间的程序员,我对基本面有一些疑问,请你澄清以下内容: 案例1:
Public Class BillItems
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
Private _BillIdValue As String
Property BillId As String
Get
Return _BillIdValue
End Get
Set(ByVal value As String)
If Not _BillIdValue = value Then
_BillIdValue = value
End If
End Set
End Property
End Class
案例2:
Public Class BillItems
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
Property BillId As String
Get
Return BillId
End Get
Set(ByVal value As String)
If Not BillId = value Then
BillId = value
End If
End Set
End Property
End Case
案例1和案例2是否产生相同的结果,我的意思是必然存在私有值?,我们可以使用属性本身在其Set和get语句中使用自己的值吗?
谢谢。
答案 0 :(得分:4)
我无法想象Case 2将在不引起堆栈溢出异常的情况下运行。你本质上是在制造一个无限循环,不断调用自己。
案例1是正确的做法。
如果你使用.Net 4,你可以这样做(没有进一步的Get / Set代码):
Property BillId As String
这将为您生成私有成员变量(_BillId
)。
编辑:
您可以尝试此操作来举起活动:
Property BillId As String
Get
Return _BillIdValue
End Get
Set(ByVal value As String)
If Not _BillIdValue = value Then
_BillIdValue = value
NotifyPropertyChanged("BillId")
End If
End Set
End Property
答案 1 :(得分:2)
在MSDN上关于Auto-Implemented Properties的这篇文章中,您可以读到当您
时属性需要标准语法Add code to the Get or Set procedure of a property, such as code to validate incoming values in the Set procedure. For example, you might want to verify that a string that represents a telephone number contains the required number of numerals before setting the property value.
因此,由于您实现了IPropertyChanged接口,因此需要向setter添加代码 并写下这样的东西。
Property BillId As String
Get
Return _BillIdValue
End Get
Set(ByVal value As String)
If Not _BillIdValue = value Then
_BillIdValue = value
NotifyPropertyChanged("BillID")
End If
End Set
End Property
第二种情况显然是错误的。 (正如其他人已经说过的无限循环)