当我访问对象的属性时,我想收集一些特定的数据。
在此示例中,每次读取属性时,计数器都会增加,但可能还需要执行其他逻辑。我想截取property方法的gettter方法,因此就可以使用我自己的一些自定义逻辑。
目前看来属性方法不可继承以自定义我自己的方法,但是也许有一种方法可以声明属性以覆盖要在属性上的方法执行之前或之后执行的方法?任何帮助将不胜感激。
示例想法:
Public Class MyObject
<MyPropertyTag()>
Property funTestValue As String
Sub testMethod()
Dim x = funTestValue `counter increases by one`
End Sub
End Class
<AttributeUsage(AttributeTargets.Property)>
Public Class MyPropertyTag
Inherits System.Attribute
Private Val
Private _counter As Long
Function [Get]()
_counter += 1
Return Val
End Function
Sub [Set](value)
Me.Val = value
End Sub
End Class
答案 0 :(得分:0)
我使用了Property过程的长格式,并在Get中增加了一个整数属性。
Public Class MyObject
Public Property NumberOfTestValueAccess As Integer
Private _funTestValue As String
Public Property funTestValue As String
Get
NumberOfTestValueAccess += 1
Return _funTestValue
End Get
Set(value As String)
_funTestValue = value
End Set
End Property
End Class
测试代码。
Private obj As New MyObject()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
obj.funTestValue = "Hello"
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim s = obj.funTestValue
MessageBox.Show($"The property value is {s} The number of times it was accessed is {obj.NumberOfTestValueAccess}")
End Sub