2009-05-14 5 views
0

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"); 
+0

@Petras J'ai mis à jour ma réponse en conséquence. –

Répondre

3

Utilisez la méthode GetCustomAttributes() sur le type de votre objet courant. Cela renvoie un tableau d'objets représentant instance (s) des attributs de ce type qui sont du type d'attribut que vous spécifiez:

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

Edit: OK, avec vos précisions, je comprends un peu mieux ce que vous êtes essayer de faire. Je pense que j'ai mal interprété votre échantillon de code la première fois. Il est essentiellement le même concept, mais l'attribut est sur un champ, et non la classe:

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; 
} 

Modifier à nouveau: Afin d'obtenir une poignée sur le terrain, vous devez connaître le type sur lequel vit sur le terrain. Un moyen facile est d'utiliser this.GetType() mais vous pouvez aussi faire quelque chose comme:

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

Voir mon commentaire dans la question. Cela ne renvoie aucun attribut – Petras

+0

@Petras J'ai mis à jour ma réponse en conséquence. –

+0

OK, ont mis à jour le mien aussi. Toujours pas tout à fait ce que je veux. – Petras

-1

Vous pouvez lire here comment faire ce que vous voulez.

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

PropertyInfo permet d'accéder aux propriétés d'un type, et non aux attributs. –

Questions connexes