2009-06-26 10 views
1

Je souhaite accéder aux attributs personnalisés d'un champ de la classe. Je veux accéder aux attributs placés sur le champ pendant le constructeur des champs. Est-ce possible?Utilisation des attributs personnalisés du constructeur interne - C#

Modifier 28/06/09 Quelque chose comme le code ci-dessous pseudo

class SpecialInt

{

int _intVal; 
int _maxVal; 
public SpecialInt() 
{ 
    //Get attribute for the instantiated specialint 
    _maxVal = GetAttribute("MaxValue") 

} }

class main()

{

[MaxValue(100)] 
SpecialInt sInt; 
public main() 
{ 
    sInt = new SpecialInt() 
} 

}

Répondre

6

Bien sûr cela est possible. Les attributs sont stockés dans des métadonnées et ceci est facilement accessible pendant la construction d'un objet.

public class Foo { 
    [Something] 
    public int Field1; 

    public Foo() { 
    FieldInfo fi = typeof(Foo).GetField("Field1"); 
    SomethingAttribute si = (SomethingAttribute)fi.GetCustomAttribute(typeof(SomethingAttribute),false)[0]; 
    // grab any Custom attribute off of Fiield1 here 
    } 
} 
+0

Ce que je veux en quelque sorte pouvoir faire. classe SpecialInt { int _intVal; int _maxVal; SpecialInt publique() { // Obtenir les attributs du instancié specialint _maxVal = GetAttribute ("MaxValue") }} classe principale() { [MaxValue (100)] SpecialInt sint; public principal() { SINT = new SpecialInt() }} et ont le constructeur pour SpecialInt connaître les attributs qui lui sont appliqués. –

1

Vous pouvez les tester de n'importe où. Les attributs sont insérés dans les métadonnées du type lorsque vous le compilez. Un type n'a pas besoin d'être instancié pour accéder aux propriétés de champ.

Questions connexes