How to determine the code attribute to which type it applies?

public class SomeAttr: Attribute
{
    void Method()
    {
        //here I want to know the type this instance of attribute is applied to
    }
}
+3
source share
2 answers

In normal .NET, this is not so and cannot (unless you specify it manually); Sorry. You will need to add a few typeof(Foo)to the constructor / attribute properties. If you say AOP (PostSharp, etc.), then all bets are disabled.

If you mean some attributes used TypeDescriptor( [DisplayName], [TypeConverter]etc.), then there may be other options - but rather specific and non-trivial ones to implement.

+2
source

Pass the type (using typeof) to the attribute constructor, for example.

class SomeAttr : Attribute
{
    private Type _type;

    public SomeAttr(Type type)
    {
        _type = type;
    }

    private void Method()
    {
        string s = _type.ToString(); // Example usage of type.
    }
}
+2
source

Source: https://habr.com/ru/post/1719115/


All Articles