2011-01-20 68 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()); 

實際上不是你所期望的特性。