反思:如果该属性具有非公共(私有/受保护)Setter,如何从属性信息对象中查找?

WPF*_*-it 3 vb.net reflection setter private

我搜索了论坛/互联网解决方案上如何PropetryInfo对象(公共属性的)可以揭示如果它有一个私人\受保护的二传手......这一切都是徒劳的....所有帮助我发现了有关如何具有私人二传手的公共财产的"设定"值...

我想知道如果我有一个属性的PropertyInfo对象,我怎么知道它的Setter是非公共的?

我试过,在一个异常处理块中,我做了一个PropertyInfo对象的GetValue,然后通过设置相同的值来调用SetValue ......但令我惊讶的是它工作得很好而且没有错误.

帮助会非常接近......

例如

Public Class Class1
Public Property HasContextChanged() As Boolean
    Get
        Return _hasContextChanged
    End Get
    Protected Set(ByVal value As Boolean)
        _hasContextChanged = value
    End Set
End Property

Public Function CanWriteProperty(Optional ByVal propName As String = "HasContextChanged") As Boolean
    Dim prInfo As PropertyInfo = Me.GetType.GetProperty(propName)
    If prInfo Is Nothing Then Return False
    If Not prInfo.CanWrite Then
        Return False
    Else
        Try
            Dim value As Object = prInfo.GetValue(ownObj, Nothing)
            prInfo.SetValue(ownObj, value, Nothing) 'Works for Private Setter
        Catch ex As Exception
            Return False 'Not coming here whatsoever
        End Try
    End If
    Return True
End Function
Run Code Online (Sandbox Code Playgroud)

结束班

谢谢

Vinit sankhe.

Ada*_*hes 7

一旦你拥有PropertyInfo的财产,你可以调用它的GetSetMethod函数返回MethodInfo的set访问.然后,您可以检查MethodInfoIsPublic属性,看看set访问是公开的.

Dim prInfo As PropertyInfo = Me.GetType.GetProperty(propName)
Dim method as MethodInfo = prInfo.GetSetMethod()
If Not method.IsPublic Then
    Return False
Else
    Dim value As Object = prInfo.GetValue(ownObj, Nothing)
    prInfo.SetValue(ownObj, value, Nothing) 'Works for Private Setter
End If
Run Code Online (Sandbox Code Playgroud)