2011-01-20 52 views
0

我创建了一个自定义属性&在我的课程的属性(不是字段)中使用它。.NET MemberInfo.GetCustomAttributes不能用于类的属性!

当我打电话FormatterServices.GetSerializableMembers,它确实给我的所有属性

但是当我尝试读取使用MemberInfo.GetCustomAttributes属性,它不给我任何价值。

当我尝试实现相同的使用object.GetType()。GetProperties()。GetCustomAttributes,它完美的作品。

任何想法为什么它没有提供MemberInfo中的信息?

[AttributeUsage(AttributeTargets.Property)] 
public class MyAttribute : Attribute { } 

//DOES NOT WORK 
MemberInfo[] members = FormatterServices.GetSerializableMembers(recordObject.GetType()); 
object[] attributes = members[0].GetCustomAttributes(typeof(MyAttribute), false) 

//WORKS 
PropertyInfo[] properties = recordObject.GetType().GetProperties(); 
object[] attributes = properties[0].GetCustomAttributes(typeof(MyAttribute), false); 
+0

您能否构建一个简短但完整的例子来演示问题并将其添加到您的问题中? – 2011-01-20 13:28:55

回答

2

FormatterServices.GetSerializableMembers不返回任何属性,而是返回可序列化类的字段。

因此,对于下面的示例类的实例:

[Serializable] 
    public class TestClass 
    { 
     private int _test; 

     [MyAttribute] 
     public int Test 
     { 
      get { return _test; } 
      set { _test = value; } 
     } 
    } 

FormatterServices.GetSerializableMembers_test领域获取使用MemberInfo,但的GetType()的GetProperties()与物业的回报MemberInfo

而且由于该字段本身没有附加任何属性,因此GetCustomAttributes不会返回任何内容。

+0

我非常同意你的看法,但从.net中看到你不能以这种方式阅读属性的属性。 – 2011-01-21 05:45:47

1

最有可能的第一个成员

返回
FormatterServices.GetSerializableMembers(recordObject.GetType()); 

实际上不是你所期望的特性。

相关问题