Han*_*abi 7 c# linq extension-methods custom-attributes
下面我有一个解决方案,用扩展方法从字段中获取属性.现在我想用方法而不是字段做类似的事情.
public static MemberInfo GetMember<T, R>(this T instance, Expression<Func<T, R>> selector)
{
var member = selector.Body as MemberExpression;
return member?.Member;
}
public static T GetAttribute<T>(this MemberInfo meminfo) where T : Attribute
{
return meminfo.GetCustomAttributes(typeof(T)).FirstOrDefault() as T;
}
Run Code Online (Sandbox Code Playgroud)
用法:
var attr = this.GetMember(x => x.AddButtonVisibility).GetAttribute<Test>();
Run Code Online (Sandbox Code Playgroud)
所以在我的情况下,用法应该是这样的:
var attr = this.GetMethod(x => x.SomeMethod).GetAttribute<Test>();
Run Code Online (Sandbox Code Playgroud)
这有可能以任何方式或我必须尝试完全不同的东西吗?
您可以执行以下操作:
public static MethodInfo GetMethod<T>(this T instance, Expression<Action<T>> selector)
{
var member = selector.Body as MethodCallExpression;
return member?.Method;
}
public static MethodInfo GetMethod<T, R>(this T instance, Expression<Func<T, R>> selector)
{
var member = selector.Body as MethodCallExpression;
return member?.Method;
}
Run Code Online (Sandbox Code Playgroud)
请注意,您需要以void不同方式处理方法,因为Func<T, R>没有意义,您需要重载Action<T>.