GetCustomAttributes

时间:2010-09-13 17:44:09

标签: .net vb.net reflection

    <AttributeUsage(AttributeTargets.Property)> _
Private Class CustomAttrib
    Inherits Attribute

    Public Property DataTypeLength As Integer

End Class

Private Class TestClass
    <CustomAttrib(DataTypeLength:=75)> _
    Public Property MyProp As String
End Class

Dim properties = GetType(TestClass).GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)

For each Prop As FieldInfo in Properties

    Dim attributes =    DirectCast(prop.GetCustomAttributes(GetType(TestClass), False), CustomAttrib())

  If Attributes.Any Then
    'get value of custom attribute
  End If
Next

好的,无论我做什么,属性总是空/无。我也尝试了以下内容:

Attribute.GetCustomAttributes(prop)

这会返回CompilerGeneratedAttributeDebuggerBrowsableAttribute

类型的两个属性

我在这里做错了什么?

4 个答案:

答案 0 :(得分:3)

这里的问题是你已经声明了一个自动实现的属性,但是要求在字段上定义属性。自动实现的属性将具有支持字段,但编译器不会将自定义属性从属性复制到支持字段。因此,你没有看到任何。

解决此问题的方法是将调用从GetFields切换到GetProperties。此外,Hans指出您需要查找公共非私有实体,并且需要查找自定义属性类型CustomAttrib而不是类TestClass

Dim properties = GetType(TestClass).GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public)

答案 1 :(得分:2)

  

Dim properties = GetType(TestClass).GetFields(...)

您正在尝试检索属性,但您使用了 GetFields 。改为使用GetProperties。

下一个问题是你传递的BindingFlags。您要求私有财产,但该类只有公共属性。还包括 BindingFlags.Public

下一个问题是你传递GetCustomAttributes()的类型,你要搜索CustomAttrib,而不是类类型。

修正:

    Dim properties = GetType(TestClass).GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or BindingFlags.Public)
    For Each Prop As PropertyInfo In properties
        Dim attributes = DirectCast(Prop.GetCustomAttributes(GetType(CustomAttrib), False), CustomAttrib())
        If attributes.Length > 0 Then
            ''get value of custom attribute
        End If
    Next

答案 2 :(得分:0)

Dim attributes = DirectCast(prop.GetCustomAttributes(GetType(CustomAttrib), False), CustomAttrib())

答案 3 :(得分:0)

正如 JaredPar 已充分陈述,这与你的绑定标志有关。这揭示了关于反思的一般教训 - 大多数方法都很挑剔你使用的标志。有些不直观。如果您遇到问题,请使用绑定标记,并尝试选择您认为适用于您要搜索的成员类型的所有内容。

相关问题