views:

335

answers:

1

Hi there

I am trying to determine the type of a property which an attribute relates to, from within the attributes constructor. More specificity I am looking for the class which contains the property.

my current constructor looks like this:

    public IndexedCategoryAttribute(Type DefiningClass, String HeaderText, int Index)
    {

        this._definingClass = DefiningClass;

however I want it to look like:

   public IndexedCategoryAttribute(String HeaderText, int Index)
    {

        PropertyInfo Info = ???
        this._definingClass = Info.DeclaringType;

I believe that this will provide safer code for users of the attribute since at present it requires a 'typeof(MyClass)' in the the Attribute definition, which opens the posiblity of the wrong type being supplied?

For further information, I am using this with the propertygrid. The type is used in a static Dictionary<Type, Dictionary<String, int>> for grouping category's to the class they relate to.

+2  A: 

I don't think attributes, when instantiated, can know the type or property to which they are being associated.

The relationship goes the other way:

  • properties have attributes
  • types have attributes
  • methods have attributes

Attributes do not "have" types.

When building your grid, you should do the scan in the opposite direction from what you proposed. For each type in your set, you can reflect to determine the attributes attached to the type (or dive into attributes on the property), and if those attributes are your category attribute, add to the dictionary.

Cheeso
Thanks, I was hoping that I could keep everything to do with the indices within the Attribute itself, however I can indeed do it in the type descriptor