[英]How to intercept the class property setter using the attributes
I want to count the number of times some specific property was set. 我想计算设置某些特定属性的次数。 I can do it like that: 我可以这样:
Class Test
Private changeCounter As New Dictionary(Of String, Integer)
Private _myProp1 As String
Public Property MyProp1() As String
Get
Return _myProp1
End Get
Set(ByVal value As String)
_myProp1 = value
If Not changeCounter.ContainsKey("MyProp1") Then
changeCounter.Add("MyProp1", 0)
End If
changeCounter("MyProp1") += 1
End Set
End Property
Private _myProp2 As String
Public Property MyProp2() As String
Get
Return _myProp2
End Get
Set(ByVal value As String)
_myProp2 = value
If Not changeCounter.ContainsKey("MyProp2") Then
changeCounter.Add("MyProp2", 0)
End If
changeCounter("MyProp2") += 1
End Set
End Property
Public Sub Print()
For Each pair In changeCounter
Console.WriteLine("{0} : {1}", pair.Key, pair.Value)
Next
End Sub
End Class
Usage: 用法:
Dim t As New Test
t.MyProp1 = "value 1"
t.MyProp1 = "value 2"
t.MyProp2 = "value 3"
t.Print()
'Output
MyProp1 : 2
MyProp2 : 1
I'm wondering if the same could be achieved using some custom attributes in order to make the code much cleaner. 我想知道是否可以使用一些自定义属性来实现相同目的,以使代码更加简洁。 Something like: 就像是:
Class Test
Private changeCounter As New Dictionary(Of String, Integer)
<SomeCustomAttribute("MyProp1", ...)>
Public Property MyProp1() As String
<SomeCustomAttribute("MyProp2", ...)>
Public Property MyProp2() As String
Public Sub Print()
For Each pair In changeCounter
Console.WriteLine("{0} : {1}", pair.Key, pair.Value)
Next
End Sub
End Class
Why not just use an internal private function? 为什么不只使用内部私有功能?
Class Test
Private changeCounter As New Dictionary(Of String, Integer)
Private _myProp1 As String
Public Property MyProp1() As String
Get
Return _myProp1
End Get
Set(ByVal value As String)
_myProp1 = value
CountChange("MyProp1")
End Set
End Property
Private _myProp2 As String
Public Property MyProp2() As String
Get
Return _myProp2
End Get
Set(ByVal value As String)
_myProp2 = value
CountChange("MyProp2")
End Set
End Property
Public Sub Print()
For Each pair In changeCounter
Console.WriteLine("{0} : {1}", pair.Key, pair.Value)
Next
End Sub
Private Sub CountChange(ByVal PropName As String)
If Not changeCounter.ContainsKey(PropName) Then
changeCounter.Add(PropName, 0)
End If
changeCounter("MyProp1") += 1
End Sub
End Class 末级
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.