2015-04-24 94 views
0

我有一個類和接口的設置是這樣的:無法擺脫的PropertyInfo屬性C#

public partial interface INav_Item 
{ 
     [FieldID("df918977-369c-4a06-ac38-adb8741b5f75")] 
     string Title {get; set;} 
} 


public partial class Nav_Item : INav_Item 
{ 
     [FieldID("df918977-369c-4a06-ac38-adb8741b5f75")] 
     public virtual string Title {get; set;} 
} 

然後我繼承了這個類:

public class MenuItem : Nav_Item 
{ 
     public virtual IEnumerable<MenuItem> Children { get; set; } 

     //some other properties 
} 

現在我試圖實例化對象類型MenuItem,並嘗試從繼承類中獲取屬性(我無法直接實例化MenuItem,因爲該類型正從其他類中傳入)

object obj = Activator.CreateInstance(type); 

foreach (PropertyInfo propInfo in type.GetProperties()) 
{ 
      FieldAttribute sfi =(FieldAttribute)propInfo.PropertyType.GetCustomAttribute(typeof(FieldAttribute)); 

} 

但這是給我sfinull。我也調試儘量讓所有的屬性:

propInfo.PropertyType.GetCustomAttributes() 

..但是這只是給我的系統屬性(類型和別的東西),但我自己的屬性,只是不存在?這是因爲這個類是繼承的嗎?我如何獲得屬性值?

編輯:

屬性類的定義是這樣的:

public class FieldIDAttribute : Attribute 
{ 
    private string _id; 

    public FieldAttribute(string Id) 
    { 
     _id = Id; 
    } 

    public ID TheFieldID 
    { 
     get 
     { 
      return new ID(_id); 
     } 
    } 
} 

回答

1

不,它不是繼承的問題。你需要改變這一點:

FieldAttribute sfi =(FieldAttribute)propInfo.PropertyType 
    .GetCustomAttribute(typeof(FieldAttribute)); 

這樣:

var sfi = propInfo.GetCustomAttribute(typeof(FieldIDAttribute)) as FieldIDAttribute; 

這是因爲PropertyType返回屬性的,你的情況的類型,即string。而string類型沒有您的自定義屬性。

此外,您編輯的FieldIDAttribute類是不正確的。它的構造函數與類名稱不匹配,它具有未聲明的&不正確的ID類型。

0

除了亞歷克斯說,你應該指定綁定標誌,這個工作對我來說:

foreach (PropertyInfo propInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) 
{ 
      FieldIDAttribute sfi = propInfo.PropertyType.GetCustomAttribute(typeof(FieldIDAttribute)) as FieldIDAttribute; 

      //Check if null here, if not, it has the attribute. 

} 

編輯:「類型」必須是Nav_Item,你沒有FieldIDAttribute應用到任何東西在Menu_item類中。爲了獲取IEnumerable的屬性,您必須枚舉它並讀取列表中每種元素的屬性。

+0

不,那不是真的。如果你沒有指定綁定標誌,它就會在'typeof(MenuItem)'上包含基類public屬性。在他特定的代碼示例中(帶有一個實例),他可以使用更簡單的方法:'TypeDescriptor.GetProperties(obj)' – Alex