我有一个属性类,一个父母和它的孩子:
class DisplayInfo : Attribute {
public string Name { set; get; }
public DisplayInfo(string name) {
Name = name;
}
}
class A {
[DisplayInfo("This is Alma")]
public string Alma {set;get;}
}
class B : A {
[DisplayInfo("This is Beta")]
public string Beta {set;get;}
}
我想从属性及其实例B的值中获取一个列表。这是我的代码:
IEnumerable<MemberInfo> sourceProperties = from source in sourceType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
// where sourceType is typeof(B)
DisplayInfo di;
foreach (MemberInfo mi in sourceProperties) {
di = (DisplayInfo)mi.GetCustomAttribute<DisplayInfo>();
ret.Add(string.Format("{0}:{1}",
di != null
? di.Name
: mi.Name,
B_instance.GetType().GetProperty(mi.Name).GetValue(B_instance, null)));
}
它适用于B类的所有直接领域,但当然没有列出A中的字段。我怎样才能实现它们?
答案 0 :(得分:1)
使用GetCustomAttribute的其他重载:
https://msdn.microsoft.com/en-us/library/hh138307(v=vs.110).aspx
// parameter: inherit => true
di = (DisplayInfo)mi.GetCustomAttribute<DisplayInfo>(true);