C# 从 methodinfo 获取委托
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/940675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a delegate from methodinfo
提问by Ty.
I have a drop down list that is populated by inspecting a class's methods and including those that match a specific signature. The problem is in taking the selected item from the list and getting the delegate to call that method in the class. The first method works, but I cannot figure out part of the second.
我有一个下拉列表,它通过检查类的方法并包括与特定签名匹配的方法来填充。问题在于从列表中获取所选项目并让委托在类中调用该方法。第一种方法有效,但我无法弄清楚第二种方法的一部分。
For example,
例如,
public delegate void MyDelegate(MyState state);
public static MyDelegate GetMyDelegateFromString(string methodName)
{
switch (methodName)
{
case "CallMethodOne":
return MyFunctionsClass.CallMethodOne;
case "CallMethodTwo":
return MyFunctionsClass.CallMethodTwo;
default:
return MyFunctionsClass.CallMethodOne;
}
}
public static MyDelegate GetMyDelegateFromStringReflection(string methodName)
{
MyDelegate function = MyFunctionsClass.CallMethodOne;
Type inf = typeof(MyFunctionsClass);
foreach (var method in inf.GetMethods())
{
if (method.Name == methodName)
{
//function = method;
//how do I get the function to call?
}
}
return function;
}
How do I get the commented out section of the second method to work? How do I cast the MethodInfo
into the delegate?
如何让第二种方法的注释掉部分起作用?我如何将MethodInfo
转换为委托?
Thanks!
谢谢!
Edit: Here is the working solution.
编辑:这是工作解决方案。
public static MyDelegate GetMyDelegateFromStringReflection(string methodName)
{
MyDelegate function = MyFunctionsClass.CallMethodOne;
Type inf = typeof(MyFunctionsClass);
foreach (var method in inf.GetMethods())
{
if (method.Name == methodName)
{
function = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), method);
}
}
return function;
}
采纳答案by Nate Kohari
You'll need to call some form of Delegate.CreateDelegate(), depending on whether the method in question is a static or instance method.
您需要调用某种形式的Delegate.CreateDelegate(),具体取决于所讨论的方法是静态方法还是实例方法。
回答by Sagi
public static Delegate CreateDelegate(this MethodInfo methodInfo, object target) {
Func<Type[], Type> getType;
var isAction = methodInfo.ReturnType.Equals((typeof(void)));
var types = methodInfo.GetParameters().Select(p => p.ParameterType);
if (isAction) {
getType = Expression.GetActionType;
}
else {
getType = Expression.GetFuncType;
types = types.Concat(new[] { methodInfo.ReturnType });
}
if (methodInfo.IsStatic) {
return Delegate.CreateDelegate(getType(types.ToArray()), methodInfo);
}
return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name);
}