我想编写一个方法来分析仅知道方法信息的任何方法(具有任意数量的参数和任何返回类型)的自定义属性。
此函数将检查方法是否具有特定属性。像这样:var tmp = methodInfo.GetCustomAttributes(typeof(LineItemAttribute),false);
如果它有这样的属性,它就会执行它。我想让调用那个函数真的很容易使用。因此,在示例中,我想调用三种方法和方法 GetMethodAttributes
。
class Test
{
public static void Main()
{
}
public void Test1(){}
public void Test2(int a){}
public void Test3(object a, string c, Boolean d);
public void GetMethodAttributes(MethodInfo mi) {}
}
理想情况下我想写这样的东西
public static void Main()
{
var t = new Test();
GetMethodAttributes(t.Test1);
GetMethodAttributes(t.Test2);
GetMethodAttributes(t.Test3);
}
我不想使用方法名称的字符串表示,因为方法名称可能会改变,就像这样:
MethodInfo info = type.GetMethod(name);
我有什么选择吗?基本上我需要一种方法来将委托(delegate)用于具有不同签名的函数
最佳答案
作为Chris Sinclair在上面的评论中指出;您可以在不使用反射或表达式树的情况下使用委托(delegate)来获取 MethodInfo
.缺点是编译器无法推断通用参数,因此您必须指定委托(delegate)类型以匹配给定方法的签名,如下所示:
public class Test
{
public static void Main()
{
var t = new Test();
CheckMethodAttributes<Action>(t.Test1);
CheckMethodAttributes<Action<int>>(t.Test2);
CheckMethodAttributes<Action<object, string, bool>>(t.Test3);
}
public void Test1() { }
public void Test2(int a) { }
public void Test3(object a, string c, bool d) { }
public static void CheckMethodAttributes<T>(T func)
{
MethodInfo method = new MethodOf<T>(func);
// Example attribute check:
var ignoreAttribute = method.GetAttribute<IgnoreAttribute>();
if (ignoreAttribute != null)
{
// Do something here...
}
}
}
这使用了两个实用程序类,MethodOf<T>
用于提取 MethodInfo
来自给定的 Delegate
还有一些AttributeUtils
获取强类型自定义属性检索:
public static class AttributeUtils
{
public static bool HasAttribute<TAttribute>(this MemberInfo member, bool inherit = true)
where TAttribute : Attribute
{
return member.IsDefined(typeof(TAttribute), inherit);
}
public static TAttribute GetAttribute<TAttribute>(this MemberInfo member, bool inherit = true)
where TAttribute : Attribute
{
return member.GetAttributes<TAttribute>(inherit).FirstOrDefault();
}
public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this MemberInfo member, bool inherit = true)
where TAttribute : Attribute
{
return member.GetCustomAttributes(typeof(TAttribute), inherit).Cast<TAttribute>();
}
}
public class MethodOf<T>
{
public MethodOf(T func)
{
var del = func as Delegate;
if (del == null) throw new ArgumentException("Cannot convert func to Delegate.", "func");
Method = del.Method;
}
private MethodInfo Method { get; set; }
public static implicit operator MethodOf<T>(T func)
{
return new MethodOf<T>(func);
}
public static implicit operator MethodInfo(MethodOf<T> methodOf)
{
return methodOf.Method;
}
}
关于c# - 获取具有任何签名的任何方法的 MethodInfo(任何签名的委托(delegate)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329433/