Access to the value of a Custom Attribute

前端 未结 7 2282
夕颜
夕颜 2021-01-03 20:17

I\'ve got this custom attribute:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
class MethodTestingAttibute : Attribute
{           


        
相关标签:
7条回答
  • 2021-01-03 20:47

    Necromancing.
    For those that still have to maintain .NET 2.0, or those that want to do it without 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);
    }
    

    Example usage:

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

    or in your case simply

    MethodInfo mi = typeof(Vehicles).GetMethod("m1");
    string aValue = GetAttributValue<MethodTestingAttibute, string>(mi, a => a.Value);
    
    0 讨论(0)
提交回复
热议问题