0
我想统计一些特定属性的设置次数。 我能做到这样的:如何拦截使用属性的类属性设置器
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
用法:
Dim t As New Test
t.MyProp1 = "value 1"
t.MyProp1 = "value 2"
t.MyProp2 = "value 3"
t.Print()
'Output
MyProp1 : 2
MyProp2 : 1
我的属性想知道如果同样的可以用一些自定义来实现,以使代码更清洁。例如:
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
你这样做没有属性的方式似乎罚款,你为什么要使用属性? – Ric
@Ric我有很多属性,我不想重复每个人几乎相同的代码。 –