【发布时间】:2013-01-15 00:48:27
【问题描述】:
我想编写一个方法来分析任何方法的自定义属性(具有任意数量的参数和任何返回类型),只知道方法信息。
此函数将检查方法是否具有特定属性。像这样: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);
我有什么选择吗?基本上我需要一种方法来为具有不同特征的函数使用委托
【问题讨论】:
-
GetMethodAttributes是做什么的,什么也没返回,你希望GetMethodAttributes(t.Test1);做什么? -
这个函数会检查方法是否有特定的属性。像这样: var tmp = methodInfo.GetCustomAttributes(typeof(LineItemAttribute),false); 如果它有这样的属性,它会执行它。
-
假设
public void Test3(object a, string c, Boolean d);有属性,不传入任何参数你将如何执行 -
在 Eric Lippert 的博客中:In Foof We Trust: A Dialogue
-
使用隐式运算符有一种非常简洁的方法,甚至适用于重载解决方案:stackoverflow.com/a/3472250/1269654 编辑:那里的示例使用静态方法,但它也适用于实例方法(不要'甚至不需要实例化实例,只需在编译时引用类型化的 null 值就可以了)
标签: c# reflection delegates