【问题标题】:How to get attributes from a property if I don't know if they are in the interface or concrete class?如果我不知道属性是在接口还是具体类中,如何从属性中获取属性?
【发布时间】:2014-12-11 11:56:37
【问题描述】:

我有以下代码:

public interface IFoo
{
    [DisplayName("test")]
    string Name { get; set; }
}

public class Foo : IFoo
{
    public string Name { get; set; }
}

使用反射我需要从属性Name 中获取属性。但是我不知道我将收到的Type 是接口还是具体类。

如果我尝试在具体类上执行prop.GetCustomAttributes(true),它不会返回我在界面上设置的属性。我希望它在这种情况下返回。

是否有一种方法可以获取在具体类和接口上定义的属性?或者我该如何处理?

【问题讨论】:

标签: c# reflection


【解决方案1】:

没有内置方法可以做到这一点,但你可以写一个:

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>();

【讨论】:

    【解决方案2】:

    班级doesn't inherit the attributes from the interface。因此,您必须致电Type.GetInterfaces() 来查找接口,并尝试查找其属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2019-04-08
      • 2012-10-16
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      相关资源
      最近更新 更多