Considérez l'attribut personnalisé suivant:ASP.NET peut un objet obtient ses attributs
[Abc.Text(MaxLength=33)]
public Abc.Text heading = new Abc.Text();
MaxLength est défini dans la TextAtrribute de classe:
public class TextAttribute : Attribute
{
public int MaxLength {get; set;}
}
Dans un autre code que j'ai, les besoins de la classe Text connaître sa longueur maximale.
Est-il possible que je pouvais faire quelque chose comme ceci:
int max = (int)heading.GetAttribute("MaxLength");
Commentaires sur les réponses
Cette modification de la réponse de RexM a travaillé:
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;
}
Mais j'espérais pourrait le faire sans la référence à "this", le parent du champ. Pouvez-vous obtenir le parent d'un champ en quelque sorte? Cela résoudre par exemple
System.Reflection.FieldInfo headingField = heading.GetParent().GetType().GetField("heading");
@Petras J'ai mis à jour ma réponse en conséquence. –