views:

56

answers:

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

Thanks!!

+2  A: 

In regular .NET, it doesn't and can't (unless you tell it manually); sorry. You'll need to include some typeof(Foo) in the attribute constructor / properties. If you are talking AOP (PostSharp etc), then all bets are off.

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

Marc Gravell
Marc, could you give me links where I can see how it's done with AOP?
Dmitry
Sorry, I don't know enough about PostSharp to answer that; but since it is a rewriter, most things are possible.
Marc Gravell
+2  A: 

Pass the type (using typeof) into the Attribute constructor, e.g,.

class SomeAttr : Attribute
{
    private Type _type;

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

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