代表财产

时间:2013-12-15 20:00:17

标签: .net vb.net properties delegates

我已经看到了一些使用c#的解决方法,但是我正在使用vb.net,而且我无法调用一个属性的委托,我不知道如何,并且没有人似乎直截了当答案

所以如果有人这样做:如何为属性添加或创建委托

1 个答案:

答案 0 :(得分:0)

对于PropertyName类型TProp的属性,底层实现是2种方法:

  • function get_PropertyName() as TProp
  • sub set_PropertyName(value as TProp)

以下是字符串属性的示例:

Public Delegate Function StringGetter() As String
Public Delegate Sub StringSetter(value As String)

Class Test
    Public Property MyProp As String
End Class

Public Sub Main()

    Dim testObj As New Test With {.MyProp = "Hello"}

    Dim getter = [Delegate].CreateDelegate(GetType(StringGetter), testObj, "get_MyProp")
    If CType(getter.DynamicInvoke(), String) <> "Hello" Then Throw New Exception("get failed")

    Dim setter = [Delegate].CreateDelegate(GetType(StringSetter), testObj, "set_MyProp")
    setter.DynamicInvoke("Hello2")
    If testObj.MyProp <> "Hello2" Then Throw New Exception("set failed")

End Sub