【发布时间】:2019-11-15 03:40:10
【问题描述】:
我正在尝试使用反射将MethodInfo 转换为Func<T, TResult>。到目前为止,我的代码在某些情况下似乎可以正常工作,但我无法使用派生自另一个参数类型的参数类型创建 Func。我错过了一些东西,不幸的是我不知道如何从那里开始。我猜想某种Expression.Convert() 会是有序的,如果是这样,在哪里以及如何?
这是一个测试我想要达到的目标的简短程序。它可以复制粘贴到https://dotnetfiddle.net/ 并且应该正在编译。
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
var myObject = new MyClass();
var methodInfo = myObject.GetType().GetMethod("HelloThere");
var parameterType = methodInfo.GetParameters()[0].ParameterType;
var parameterExpression = Expression.Parameter(parameterType);
var callExpression = Expression.Call(Expression.Constant(myObject), methodInfo, parameterExpression);
var compiledFunction = Expression.Lambda<Func<EventArgs, string>>(callExpression, parameterExpression).Compile();
}
public class MyClass
{
public string HelloThere(StringEventArgs args)
{
return "General Kenobi";
}
}
public class StringEventArgs : EventArgs
{
public StringEventArgs(string aString)
{
Value = aString;
}
public string Value { get; set; }
}
}
但是,运行时会抛出以下错误:
Run-time exception (line 13): ParameterExpression of type 'Program+StringEventArgs' cannot be used for delegate parameter of type 'System.EventArgs'
【问题讨论】:
标签: c# type-conversion delegates expression func