[英]C# delegate casting from MethodInfo.Getmethod()
我正在编写对函数进行数学运算的程序。 我希望用户输入 function 所以我写了 class 它用所需的方法制作源代码,编译它并将方法保存为委托。 这个方法被传递给我的另一个 class 的构造函数,它存储在委托中。 问题是:它不起作用。 发生 InvalidCastException。
(我做到了,所以我不必编写自己的数学解析器。诸如 Math.Pow(x, 2) * Math.Sin(x) 之类的表达式应该没问题,不需要 x^2*sin( x) 工作)
[已编辑] 现在我使用
Func<decimal, decimal>
委托传递的地方(到 class Function: public Function(func f, decimal l) 的构造函数):
Func<decimal, decimal> function = new Func<decimal, decimal>(MathParser.MakeExpr(inputTextBox.Text));
F = new Function(function, l);
生成所需委托的内容:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Windows.Forms;
namespace Furry
{
internal class MathParser
{
private static string begin =
@"using System;
namespace Parser
{
public delegate decimal func(decimal x);
public static class LambdaCreator
{
public static decimal Create()
{
return (x)=>";
private static string end = @";
}
}
}";
public static Func<decimal, decimal> MakeExpr(string Expr)
{
string middle = Expr;
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters
{
GenerateInMemory = true
};
parameters.ReferencedAssemblies.Add("System.dll");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, begin + middle + end);
Type cls = results.CompiledAssembly.GetType("Parser.LambdaCreator");
MethodInfo method = cls.GetMethod("Create", BindingFlags.Static | BindingFlags.Public);
Delegate f = method.Invoke(null, null) as Delegate;
//MessageBox.Show(f.DynamicInvoke(5m).ToString()); doesn't work
return (Func<decimal, decimal>)f;
}
}
}
还尝试调用:
Func<decimal, decimal> f = method.Invoke(null, null) as Func<decimal, decimal>;
现在发生 FileNotFoundException。 FileNotFoundException:无法加载文件或程序集“file:///C:\Users\Adefe\AppData\Local\Temp\trd2ig0g.dll”或其依赖项之一。 找不到指定的文件。
解决方案:MathParser class:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
namespace Furry
{
internal class MathParser
{
private static string begin =
@"using System;
namespace Parser
{
public delegate decimal func(decimal x);
public static class LambdaCreator
{
public static Func<decimal, decimal> Create()
{
return (x)=>";
private static string end = @";
}
}
}";
public static Func<decimal, decimal> MakeExpr(string Expr)
{
string middle = Expr;
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters
{
GenerateInMemory = true
};
parameters.ReferencedAssemblies.Add("System.dll");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, begin + middle + end);
Type cls = results.CompiledAssembly.GetType("Parser.LambdaCreator");
MethodInfo method = cls.GetMethod("Create", BindingFlags.Static | BindingFlags.Public);
Delegate f = method.Invoke(null, null) as Delegate;
return (Func<decimal, decimal>)f;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.