如何使用属性拦截类属性setter

时间:2015-09-25 08:47:42

标签: .net vb.net

我想计算一些特定属性的设置次数。 我可以这样做:

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

1 个答案:

答案 0 :(得分: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
            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

结束班