【问题标题】:How can a property resolve its own name and type with reflection?属性如何通过反射解析自己的名称和类型?
【发布时间】:2011-01-26 22:57:58
【问题描述】:

有没有办法让属性在运行时使用反射访问自己的名称和类型?我想在不硬编码类中属性的名称或索引的情况下访问此信息。

简单示例代码:

Private ReadOnly Property MyProperyName() As String
    Get
        Console.WriteLine((Get Current Property Info).Type.ToString)
        Console.WriteLine((Get Current Property Info).Name)
        Return ""
    End Get
End Property

预期输出:

System.String
MyPropertyName

【问题讨论】:

    标签: vb.net reflection properties


    【解决方案1】:

    您可以使用StackTrace 获取当前方法:

    Dim currentMethod = CType(new StackTrace(0, false).GetFrame(0).GetMethod(), _ 
        System.Reflection.MethodInfo)
    

    如果你可以假设你在一个属性中,那么你可以去掉方法名前面的“get_”:

    Dim propertyName as string = currentMethod.Name.SubString(4)
    

    并使用ReturnType 作为属性类型:

    Dim propertyType as Type = currentMethod.ReturnType
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多