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我有很多屬性,我不想重複每個人幾乎相同的代碼。 –