为什么自定义类型属性不在泛型中继承?

时间:2018-02-21 13:29:35

标签: c# .net generics

我有属性

[AttributeUsage(AttributeTargets.Class)]
public class CacheAttribute : Attribute
{        
}

和泛型类

[Cache]    
public class BaseClass<T>
{        
}

和另一个班级

public class ImplClass : BaseClass<Type>
{        
}

当我尝试从

获取自定义属性时
BaseClass<Type>

我得到了我的属性,但不是来自

ImplClass 

获取自定义属性的代码是

typeof(ImplClass).CustomAttributes -> 0
typeof(BaseClass<Type>).CustomAttributes -> 1

如何将属性继承到我的实现?

  

注意:类似的问题How does inheritance work for Attributes? 无用。与该问题不同,这个问题与属性继承和泛型有关。

1 个答案:

答案 0 :(得分:2)

您的子类继承了您的属性 。您遇到的问题并非特定于泛型。它可以使用非泛型类型轻松复制:

using System.Linq;

[AttributeUsage(AttributeTargets.Class)]
public class FooAttribute : Attribute
{
    private readonly string name;

    public FooAttribute(string name)
    {
        this.name = name;
    }
}

[Foo("bar")]
public class Base { }
public class Child : Base { }

Console.WriteLine(typeof(Base).CustomAttributes.Count());  // Prints 1.
Console.WriteLine(typeof(Child).CustomAttributes.Count()); // Prints 0.

来自MemberInfo.CustomAttributes的文档:

  

获取包含此成员的自定义属性的集合。

因此,此属性只获取应用于类型本身的属性,而不是继承的属性(MemberInfo调用GetCustomAttributesData中的实现,这反过来只会抛出NotImplementedException而我无法找到Type中的覆盖,所以我认为这是对的。)

但是,您可以使用其中一个MemberInfo.GetCustomAttributes重载或其中一个these扩展方法来获取继承的属性

typeof(ImplClass).GetCustomAttributes(typeof(CacheAttribute), inherit: true)