【问题标题】:How does inheritance work for Attributes?继承如何对属性起作用?
【发布时间】:2010-11-17 11:28:24
【问题描述】:

属性上的Inherited bool 属性指的是什么?

这是否意味着如果我使用属性AbcAtribute(具有Inherited = true)定义我的类,并且如果我从该类继承另一个类,那么派生类也将应用相同的属性?

为了用一个代码示例来澄清这个问题,想象一下:

[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class Random: Attribute
{ /* attribute logic here */ }

[Random]
class Mother 
{ }

class Child : Mother 
{ }

Child 是否也应用了Random 属性?

【问题讨论】:

标签: c# .net vb.net attributes


【解决方案1】:

默认启用属性继承。

您可以通过以下方式更改此行为:

[AttributeUsage (Inherited = False)]

【讨论】:

    【解决方案2】:

    是的,这正是它的意思。 Attribute

    [AttributeUsage(Inherited=true)]
    public class FooAttribute : System.Attribute
    {
        private string name;
    
        public FooAttribute(string name)
        {
            this.name = name;
        }
    
        public override string ToString() { return this.name; }
    }
    
    [Foo("hello")]
    public class BaseClass {}
    
    public class SubClass : BaseClass {}
    
    // outputs "hello"
    Console.WriteLine(typeof(SubClass).GetCustomAttributes(true).First());
    

    【讨论】:

      【解决方案3】:

      当 Inherited = true(这是默认值)时,表示您创建的属性可以被该属性修饰的类的子类继承。

      所以 - 如果您使用 [AttributeUsage (Inherited = true)] 创建 MyUberAttribute

      [AttributeUsage (Inherited = True)]
      MyUberAttribute : Attribute
      {
         string _SpecialName;
         public string SpecialName
         { 
           get { return _SpecialName; }
           set { _SpecialName = value; }
         }
      }
      

      然后通过装饰超类来使用属性...

      [MyUberAttribute(SpecialName = "Bob")]
      class MySuperClass 
      {
        public void DoInterestingStuf () { ... }
      }
      

      如果我们创建 MySuperClass 的子类,它将具有此属性...

      class MySubClass : MySuperClass
      {
         ...
      }
      

      然后实例化一个 MySubClass 的实例...

      MySubClass MySubClassInstance = new MySubClass();
      

      然后测试一下是否有属性...

      MySubClassInstance

      【讨论】:

      • 请注意默认开启属性继承。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2014-10-06
      • 2017-12-18
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多