![](/img/trans.png)
[英]Using C#, how can I access the getter/setter of a VB class's default property with parameter?
[英]How to intercept the class property setter using the attributes
我想計算設置某些特定屬性的次數。 我可以這樣:
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
為什么不只使用內部私有功能?
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
末級
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.