Consider the following custom attribute:
[Abc.Text(MaxLength=33)]
public Abc.Text heading = new Abc.Text();
MaxLength is defined in the class TextAtrribute:
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 I could 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 the reference to "this", the parent of the field. Can you get a field's parent somehow? That would solve it eg
System.Reflection.FieldInfo headingField = heading.GetParent().GetType().GetField("heading");