我有以下代码:
public interface IFoo
{
[DisplayName("test")]
string Name { get; set; }
}
public class Foo : IFoo
{
public string Name { get; set; }
}
使用反射我需要从属性Name
获取属性。但是我不知道我将收到的Type
是接口还是具体类。
如果我尝试在具体类上执行prop.GetCustomAttributes(true)
,它不会返回我在界面上设置的属性。我想在这种情况下返回。
是否有一种方法可以在具体类和接口上定义属性?或者我怎么能处理这个?
答案 0 :(得分:4)
没有内置方法可以执行此操作,但您可以编写一个:
public static T GetAttribute<T>(this PropertyInfo pi) where T : Attribute
{
var attr = pi.GetCustomAttribute<T>();
if (attr != null) return attr;
var type = pi.DeclaringType;
var interfaces = type.GetInterfaces();
foreach(var i in interfaces)
{
var p = i.GetProperties().FirstOrDefault(x => Attribute.IsDefined(x,typeof(T)));
if (p != null)
return p.GetCustomAttribute<T>();
}
return null;
}
用法:
var f = new Foo();
var prop = f.GetType().GetProperty("Name");
var attr = prop.GetAttribute<DisplayNameAttribute>();
答案 1 :(得分:2)
班级doesn't inherit the attributes from the interface。因此,您必须调用Type.GetInterfaces()
来查找接口,并尝试在其上查找属性。