If you save the default attribute value as a property ( Name in my example) when building, you can use the static attribute attribute:
using System; using System.Linq; public class Helper { public static TValue GetMethodAttributeValue<TAttribute, TValue>(Action action, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var methodInfo = action.Method; var attr = methodInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute; return attr != null ? valueSelector(attr) : default(TValue); } }
Using:
var name = Helper.GetMethodAttributeValue<MyAttribute, string>(MyMethod, x => x.Name);
My solution is based on the fact that the default value is set to build the attribute, for example:
internal class MyAttribute : Attribute { public string Name { get; set; } public MyAttribute(string name) { Name = name; } }
Mikael Engver Feb 12 '17 at 18:18 2017-02-12 18:18
source share