我有一个下拉列表,它通过检查类的方法并包括那些匹配特定签名的方法来填充。问题在于从列表中获取所选项并让委托在类中调用该方法。第一种方法起作用,但我找不出第二种方法的一部分。
例如,
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;
}如何使第二个方法的注释部分工作?如何将MethodInfo转换到委托中?
谢谢!
编辑:这是工作解决方案.
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;
}发布于 2009-06-02 17:01:47
您需要调用某种形式的Delegate.CreateDelegate(),这取决于所讨论的方法是静态方法还是实例方法。
发布于 2016-11-13 21:32:51
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);
}发布于 2022-10-30 12:16:07
下面是使用Expression.GetDelegateType()的Sagi解决方案的一个更简单的版本,而不是手动检测是否需要Action或Func:
public static Delegate CreateDelegate(this MethodInfo methodInfo, object target)
{
var parmTypes = methodInfo.GetParameters().Select(parm => parm.ParameterType);
var parmAndReturnTypes = parmTypes.Append(methodInfo.ReturnType).ToArray();
var delegateType = Expression.GetDelegateType(parmAndReturnTypes);
if (methodInfo.IsStatic)
return methodInfo.CreateDelegate(delegateType);
return methodInfo.CreateDelegate(delegateType, target);
}https://stackoverflow.com/questions/940675
复制相似问题