2011-06-30 36 views
15

Ive có này Tuỳ thuộc tính:Tiếp cận giá trị của một Custom Attribute

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

    } 
} 

Để được sử dụng như thế này:

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

Và dificulty của tôi là để có những giá trị gia tăng của "2" của the MethodTestingAttibute

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

Bây giờ tôi muốn so sánh kết quả này với Giá trị của phương pháp TestingAttibute. Làm thế nào tôi có thể làm điều đó? Tôi đang cố gắng đi lên con đường này nhưng không thành công: method.GetCustomAttributes (typeof (MethodTestAttibute), true) [0] ...

Quyền truy cập vào trường thuộc tính Custoum là gì?

+0

Tôi đang bối rối. Ý của bạn là "2", nơi bạn nói "3"? –

+0

ý tôi là 2!xin lỗi – RCPT

+0

Rất gần: [bất kỳ ai-biết-một-nhanh-cách-to-get-to-custom-thuộc tính-on-an-enum-value] (http://stackoverflow.com/questions/17772/anyone-know -a-quick-way-to-get-to-custom-thuộc tính-on-an-enum-value) – nawfal

Trả lời

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

Vui lòng xem liên kết sau, nó nhận thuộc tính của enum nhưng bạn có thể tùy chỉnh để nhận thuộc tính tùy chỉnh của mình.

Getting attribute of Enum

1

Cast đối tượng để 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

Kiểm tra mã ở đây http://msdn.microsoft.com/en-us/library/bfwhbey7.aspx

Trích:

 // 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

Để lấy giá trị của thuộc tính thuộc tính, chỉ cần truyền đối tượng được trả về bởi GetCustomAttributes():

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

Necromancing.
Đối với những người vẫn phải duy trì .NET 2.0, hoặc những người muốn làm điều đó mà không cần LINQ:

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

Ví dụ sử dụng:

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

hoặc trong trường hợp của bạn chỉ đơn giản là

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

Với thuộc tính tùy chỉnh của tôi:

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

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

tôi tạo ra một phương pháp để có được thuộc tính với các giá trị của mình:

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

Với một lớp dụ (phải là không tĩnh vì T là generic)

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

Cách sử dụng:

var customAttribute = GetAttributeCustom<MyClass>("MyMethod"); 
if (customAttribute != null) 
{ 
    Console.WriteLine(customAttribute.MyPropertyAttribute); 
} 
Các vấn đề liên quan