【发布时间】:2020-06-22 13:20:59
【问题描述】:
我正在尝试从具有输出参数的 MethodInfo 对象中获取委托。我的代码如下:
static void Main(string[] args) {
MethodInfo m = typeof(Program).GetMethod("MyMethod2");
IEnumerable<Type> paramsTypes = m.GetParameters().Select(p => p.ParameterType);
Type methodType = Expression.GetDelegateType(paramsTypes.Append(m.ReturnType).ToArray());
Delegate d = m.CreateDelegate(methodType);
Action a = (Action)d;
a();
}
我得到的是 System.InvalidCastException: Unable to cast object of type Delegate2$1 to type System.Action 在执行“Action a = (Action)d”的行中。问题是我不知道在 Action 中放入什么类型,因为我知道正确的类型不是 String,它是编译中 String (String&) 的输出等价物。
MyMethod2 有一个输出参数,我认为这就是问题所在,因为当我使用作为输入参数的 MyMethod 进行测试时,它可以工作。
public static void MyMethod2(out String outputParameter) {
outputParameter = "hey";
}
public static void MyMethod(String inputParameter) {
//does nothing
}
另外,我知道如果我使用 Dynamic Invoke 而不是普通的 Delegate 调用会更容易,但我对此不感兴趣,因为我正在尝试提高我的程序的性能。有谁知道如何做到这一点?谢谢
【问题讨论】:
标签: c# .net lambda reflection delegates