Is it possible to get a parent attribute where the class defines the child attribute?

2

Assuming I have the following hierarchy:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class GrandpaAttribute : Attribute
{
    public GrandpaAttribute() {}
}

public class ParentAttribute() : GrandpaAttribute
{
    public string Name { get; }

    public ParentAttribute(string name)
    {
        Name = name;
    }
}

public class ChildAttribute() : ParentAttribute
{
    public int Number { get; }

    public ChildAttribute(string name, int number) : base(name)
    {
        Number = number;
    }
}

In a given application, I use the ChildAttribute attribute:

public class Foo
{
    [Child("The Beast", 666)]
    public string Description { get; set; }
    public DateTime SomeDate { get; set; }
}

Doubt has arisen:

Is it possible to abstract the inheritance to understand that the Description property has the GrandpaAttribute attribute?

My intention is to get an instance of GrandaAttribute defined in a property of class Foo as ParentAttribute , ChildAttribute or any other attribute derived from it.

    
asked by anonymous 03.04.2018 / 17:06

1 answer

2

As far as I understand, you want to get into the instance of class GrandpaAttribute , for test reasons I added a First property so that the test is performed, first if the real instance is searched, and then with a cast arrives in class GrandpaAttribute , example:

using System;
using System.Reflection;

[System.AttributeUsage(AttributeTargets.Property,AllowMultiple=false, Inherited=true)]
public class GrandpaAttribute : Attribute
{
    public GrandpaAttribute() 
    {
        First = "Teste";
    }
    public string First {get;set;} 
}

public class ParentAttribute : GrandpaAttribute
{
    public string Name { get; private set; }

    public ParentAttribute(string name)
    {
        Name = name;
    }
}

public class ChildAttribute : ParentAttribute
{
    public int Number { get; private set; }

    public ChildAttribute(string name, int number) 
        : base(name)
    {
        Number = number;
    }
}

public class Foo
{
    [Child("The Beast", 666)]
    public string Description { get; set; }
    public DateTime SomeDate { get; set; }
}

public class Program
{
    public static void Main()
    {
        ChildAttribute childAttribute = typeof(Foo)
                .GetProperty("Description")
                .GetCustomAttribute<ChildAttribute>(true);      


        Console.WriteLine(((GrandpaAttribute)childAttribute).First);
    }
}

An OnLine DotNetFiddle sample

    
03.04.2018 / 17:23