ASP.NET Can an Object Get Its Attributes

Consider the following custom attribute:

[Abc.Text(MaxLength=33)]
public Abc.Text heading = new Abc.Text();

      

MaxLength is defined in the TextAtrribute class:

public class TextAttribute : Attribute
{
  public int MaxLength {get; set;}

}

      

In other code I have, the Text class needs to know its MaxLength.

Is there a way to do something like this:

int max = (int)heading.GetAttribute("MaxLength");

      

Comments on answers

This modification of RexM's answer worked:

System.Reflection.FieldInfo headingField = this.GetType().GetField("heading");
object[] attribs = headingField.GetCustomAttributes(typeof(Abc.TextAttribute), true);

if (attribs.Length == 1)
{
  int max = ((Abc.TextAttribute)attribs[0]).AbcMaxLength;
}

      

But I was hoping I could do it without referencing "this", the parent of the field. Can you get the parent of the field somehow? This would resolve it, for example

System.Reflection.FieldInfo headingField = heading.GetParent().GetType().GetField("heading");

      

0


a source to share


2 answers


Use the GetCustomAttributes () method on the type of your current object. This will return an array of objects representing instances of attributes of that type that are of the specified attribute type:

object[] attribs = this.GetType().GetCustomAttributes(typeof(Abc.Text));
if (attribs.Length == 1)
{
    int max = ((Abc.Text)attribs[0]).MaxLength;
}

      

Edit: Ok, with clarifications. I understand what you are trying to do. I think this is the first time I misread your sample code. This is essentially the same concept, but the attribute is in the field, not in the class:



System.Reflection.FieldInfo headingField = this.GetType().GetField("heading");
object[] attribs = headingField.GetCustomAttributes(typeof(Abc.Text));
if (attribs.Length == 1)
{
    int max = ((Abc.Text)attribs[0]).MaxLength;
}

      

Change again. To get a handle to a field, you need to know the type the field is in. The easy way is to use this.GetType()

, but you can also do something like:

FieldInfo headingField = typeof(MyClass).GetField("heading");

      

+3


a source


You can read here how to do what you want.



Type type = TextAttribute.GetType();
PropertieInfo pi = type.GetProperty("MaxLength");
if (pi.CanRead())
  //the value
  pi.GetValue();

      

-1


a source







All Articles