首页 > 解决方案 > 将类级别属性分配给基类,它也应该分配给所有派生类

问题描述

我有一个自定义属性

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

我在很多课程中都使用它,比如

[CustomAttribute]
    public class ClassOne: MyBaseClass
    {
     .
     .

所以我有很多从MyBaseClass派生的类,如果我想在所有类中添加这个属性,会有很多变化。我想要的是我将此属性添加到我的基类中,并且所有派生类也应该具有分配给它们的相同属性。

喜欢

[CustomAttribute]
    public class MyBaseClass
    {
     .
     .

但这并不能解决问题,我的子类仍然没有添加属性。有什么办法可以做到这一点?

标签: c#attributes

解决方案


您应该[AttributeUsage(Inherited = true)]在属性中使用属性。

[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public sealed class CustomAttribute : Attribute {
    public CustomAttribute() {
    }
}

但它的默认值已经是 true 并且派生类应该可用于您的自定义属性。我推荐下面的示例块以确保。

首先,定义属性。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
                AttributeTargets.Property | AttributeTargets.Field)]
public class InheritedAttribute : Attribute { }

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
                AttributeTargets.Property | AttributeTargets.Field,
    Inherited = false)]
public class NotInheritedAttribute : Attribute { }

[InheritedAttribute]
public class BaseA {
    [InheritedAttribute]
    public virtual void MethodA() { }
}

public class DerivedA : BaseA {
    public override void MethodA() { }
}

[NotInheritedAttribute]
public class BaseB {
    [NotInheritedAttribute]
    public virtual void MethodB() { }
}

public class DerivedB : BaseB {
    public override void MethodB() { }
}

然后,检查属性。

class Program {
    static void Main(string[] args) {
        Type typeA = typeof(DerivedA);
        Console.WriteLine($"DerivedA has Inherited attribute: {typeA.GetCustomAttributes(typeof(InheritedAttribute), true).Length > 0}");
        MethodInfo memberA = typeA.GetMethod(nameof(DerivedA.MethodA));
        Console.WriteLine($"DerivedA.MemberA has Inherited attribute: {memberA.GetCustomAttributes(typeof(InheritedAttribute), true).Length > 0}\n");

        Type typeB = typeof(DerivedB);
        Console.WriteLine($"DerivedB has NotInherited attribute: {typeB.GetCustomAttributes(typeof(NotInheritedAttribute), true).Length > 0}");
        MethodInfo memberB = typeB.GetMethod(nameof(DerivedB.MethodB));
        Console.WriteLine($"DerivedB.MemberB has NotInherited attribute: {memberB.GetCustomAttributes(typeof(NotInheritedAttribute), true).Length > 0}");

        Console.Read();
    }
}

AttributeUsageAttribute.Inherited 属性


推荐阅读