¿Cómo funciona la herencia para los atributos?


¿A qué se refiere la propiedad bool en atributos Inherited?

Significa que si defino mi clase con un atributo AbcAtribute (que tiene Inherited = true), y si me heredar de otra clase de esa clase, que la clase derivada también tendrá ese mismo atributo aplicado?

Para aclarar esta pregunta con un ejemplo de código, imagine lo siguiente:

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

[Random]
class Mother 
{ }

class Child : Mother 
{ }

¿Child también tiene aplicado el atributo Random?

Author: MrLore, 2009-08-06

2 answers

Cuando Inherited = true (que es el valor predeterminado) significa que el atributo que está creando puede ser heredado por subclases de la clase decorada por el atributo.

Así que-si crea MyUberAttribute con [AttributeUsage (Heredado = true)]

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

Luego use el Atributo decorando una super-clase...

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

Si creamos una subclase de MySuperClass tendrá este atributo...

class MySubClass : MySuperClass
{
   ...
}

Luego instanciar una instancia de MySubClass...

MySubClass MySubClassInstance = new MySubClass();

Luego prueba para ver si tiene el atributo...

MySubClassInstance

 91
Author: cmdematos.com,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-02 11:26:51

Sí Eso es precisamente lo que significa. Atributo

[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());
 13
Author: ShuggyCoUk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-05 09:46:50