【问题标题】:Is there a way to override the property accessor methods with a custom method?有没有办法用自定义方法覆盖属性访问器方法?
【发布时间】:2020-03-12 19:16:27
【问题描述】:

当我的对象的属性被访问时,我想收集一些特定的数据。

在此示例中,每次读取属性时计数器都会增加,但可能还需要执行其他逻辑。我想拦截属性方法的getter,所以我自己的一些自定义逻辑就在其中。

目前看来,为了自定义我自己的属性方法是不可继承的,但也许有一种方法可以声明属性以覆盖在属性方法之前或之后执行的方法吗?任何帮助将不胜感激。

示例想法:

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

【问题讨论】:

    标签: vb.net properties attributes accessor


    【解决方案1】:

    我使用了长格式的 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
    

    【讨论】:

    • 如果它是一个值就好了,但是我需要对对象上的所有值执行此操作,这些值可能很多,并且要处理的代码将比计数器更先进。我试图找到一个不涉及重复底层逻辑的解决方案。这就是为什么我正在寻找一种解决方案,该解决方案使用和属性或可以继承方法来执行与属性访问器等效的操作。
    猜你喜欢
    • 2012-03-29
    • 2020-08-02
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多