2011-06-30 10 views
15

Ive consiguió este atributo personalizado:El acceso al valor de una de atributos personalizados

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)] 
class MethodTestingAttibute : Attribute 
{ 
    public string Value{ get; private set; } 
    public MethodTestingAttibute (string value) 
    { 
     this.Value= value; 

    } 
} 

Para usarse como esto:

[MethodTestingAttibute("2")] 
    public int m1() {return 3; } 

Y mi dificulty es tomar el valor de "2" de la MethodTestingAttibute

object result = method.Invoke(obj, new Type[] {}); // here i get the return 

ahora quiero comparar este resultado con el valor del método TestingAttibute. como puedo hacer eso? Estoy tratando de ir a este camino pero sin éxito: method.GetCustomAttributes (typeof (MethodTestAttibute), true) [0] ...

¿Cuál es el acceso adecuado al campo del atributo Custoum?

+0

Estoy confundido. ¿Te refieres a "2" donde dijiste "3"? –

+0

quiero decir 2!lo siento – RCPT

+0

Muy cerca: [alguien-sabe-una-manera-rápida-de-obtener-a-atributos-personalizados-en-un-valor-enum] (http://stackoverflow.com/questions/17772/anyone-know -a-quick-way-to-get-to-custom-attributes-on-an-enum-value) – nawfal

Respuesta

21
var attribute = 
    (MethodTestingAttibute) 
    typeof (Vehicles) 
     .GetMethod("m1") 
     .GetCustomAttributes(typeof (MethodTestingAttibute), false).First(); 
Console.WriteLine(attribute.Value); 
1

Consulte el siguiente enlace, obtiene el atributo de una enumeración pero puede personalizarlo para obtener su atributo personalizado.

Getting attribute of Enum

1

convertir el objeto a MethodTestingAttibute:

object actual = method.Invoke(obj, null); 

MethodTestingAttibute attribute = (MethodTestingAttibute)method.GetCustomAttributes(typeof(MethodTestAttribute), true)[0]; 
string expected = attribute.Value; 

bool areEqual = string.Equals(expected, actual != null ? actual.ToString() : null, StringComparison.Ordinal); 
1

Compruebe el código aquí http://msdn.microsoft.com/en-us/library/bfwhbey7.aspx

Extracto:

 // Get the AClass type to access its metadata. 
     Type clsType = typeof(AClass); 
     // Get the type information for Win32CallMethod. 
     MethodInfo mInfo = clsType.GetMethod("Win32CallMethod"); 
     if (mInfo != null) 
     { 
      // Iterate through all the attributes of the method. 
      foreach(Attribute attr in 
       Attribute.GetCustomAttributes(mInfo)) { 
       // Check for the Obsolete attribute. 
       if (attr.GetType() == typeof(ObsoleteAttribute)) 
       { 
        Console.WriteLine("Method {0} is obsolete. " + 
         "The message is:", 
         mInfo.Name); 
        Console.WriteLine(" \"{0}\"", 
         ((ObsoleteAttribute)attr).Message); 
       } 

       // Check for the Unmanaged attribute. 
       else if (attr.GetType() == typeof(UnmanagedAttribute)) 
       { 
        Console.WriteLine(
         "This method calls unmanaged code."); 
        Console.WriteLine(
         String.Format("The Unmanaged attribute type is {0}.", 
             ((UnmanagedAttribute)attr).Win32Type)); 
        AClass myCls = new AClass(); 
        myCls.Win32CallMethod(); 
       } 
      } 
     } 
0

Para obtener el valor de una propiedad de atributo, simplemente convertir el objeto devuelto por GetCustomAttributes():

{ 
    string val; 
    object[] atts = method.GetCustomAttributes(typeof(MethodTestAttibute), true); 
    if (atts.Length > 0) 
     val = (atts[0] as MethodTestingAttibute).Value; 
} 
0

Necromancing.
Para aquellos que todavía tienen que mantener .NET 2.0, o aquellos que quieren hacerlo sin LINQ: el uso

public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t) 
{ 
    object[] objs = mi.GetCustomAttributes(t, true); 

    if (objs == null || objs.Length < 1) 
     return null; 

    return objs[0]; 
} 



public static T GetAttribute<T>(System.Reflection.MemberInfo mi) 
{ 
    return (T)GetAttribute(mi, typeof(T)); 
} 


public delegate TResult GetValue_t<in T, out TResult>(T arg1); 

public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute 
{ 
    TAttribute[] objAtts = (TAttribute[])mi.GetCustomAttributes(typeof(TAttribute), true); 
    TAttribute att = (objAtts == null || objAtts.Length < 1) ? default(TAttribute) : objAtts[0]; 
    // TAttribute att = (TAttribute)GetAttribute(mi, typeof(TAttribute)); 

    if (att != null) 
    { 
     return value(att); 
    } 
    return default(TValue); 
} 

Ejemplo:

System.Reflection.FieldInfo fi = t.GetField("PrintBackground"); 
wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi); 
string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a){ return a.Name;}); 

o en su caso, simplemente

MethodInfo mi = typeof(Vehicles).GetMethod("m1"); 
string aValue = GetAttributValue<MethodTestingAttibute, string>(mi, a => a.Value); 
0

Con mi atributo personalizado:

[AttributeUsage(AttributeTargets.Method)] 
public class AttributeCustom : Attribute 
{ 
    public string MyPropertyAttribute { get; private set; } 

    public AttributeCustom(string myproperty) 
    { 
     this.MyPropertyAttribute = myproperty; 
    } 
} 

creo un método para conseguir atribuir con sus valores:

public static AttributeCustom GetAttributeCustom<T>(string method) where T : class 
{ 
    try 
    { 
     return ((AttributeCustom)typeof(T).GetMethod(method).GetCustomAttributes(typeof(AttributeCustom), false).FirstOrDefault()); 
    } 
    catch(SystemException) 
    { 
     return null; 
    } 
} 

Con una clase de ejemplo (debe ser no es estática, porque T es genérico)

public class MyClass 
{ 
    [AttributeCustom("value test attribute")]) 
    public void MyMethod() 
    { 
     //... 
    } 
} 

Uso:

var customAttribute = GetAttributeCustom<MyClass>("MyMethod"); 
if (customAttribute != null) 
{ 
    Console.WriteLine(customAttribute.MyPropertyAttribute); 
} 
Cuestiones relacionadas