我有一個類和接口的設置是這樣的:無法擺脫的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));
}
但這是給我sfi
爲null
。我也調試儘量讓所有的屬性:
propInfo.PropertyType.GetCustomAttributes()
..但是這只是給我的系統屬性(類型和別的東西),但我自己的屬性,只是不存在?這是因爲這個類是繼承的嗎?我如何獲得屬性值?
編輯:
屬性類的定義是這樣的:
public class FieldIDAttribute : Attribute
{
private string _id;
public FieldAttribute(string Id)
{
_id = Id;
}
public ID TheFieldID
{
get
{
return new ID(_id);
}
}
}
不,那不是真的。如果你沒有指定綁定標誌,它就會在'typeof(MenuItem)'上包含基類public屬性。在他特定的代碼示例中(帶有一個實例),他可以使用更簡單的方法:'TypeDescriptor.GetProperties(obj)' – Alex