C#无法转换`System.Delegate'表达式输入`PowellMethod.fcn_delegate'

时间:2015-01-04 12:47:23

标签: c# delegates

我正在尝试将在运行时编译的C#函数提供给类。

我收到以下错误: 参数#1' cannot convert System.Delegate'表达式以输入`PowellMethod.fcn_delegate'

在Main class.css中

    public delegate void fcn_delegate(int n, double[] x, double[] f, int iflag);
static void Main()
{

    PowellMethod powell = new PowellMethod();

    MethodInfo function = CreateFunction(StringFunction); // the function contents defined as a string
    var betterFunction = (Func<int, double[], double[], int>)Delegate.CreateDelegate(typeof(Func<int, double[], double[], int>), function);

    Delegate test = (fcn_delegate) Delegate.CreateDelegate(typeof(fcn_delegate), function);

    //powell.dnsqe_nice(betterFunction,0, x,tol,bounds,ref fnorm,ref info);
    powell.dnsqe_nice(test,0, x,tol,bounds,ref fnorm,ref info);


}

public static MethodInfo CreateFunction(string function)
{
    string code = @"
            using System;

            namespace UserFunctions
            {                
                public class BinaryFunction
                {                
                    public static void Function(int n, double[] x, double[] f, int iflag)
                    {
                        func_xy;
                    }
                }
            }
        ";

    string finalCode = code.Replace("func_xy", function);

    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), finalCode);

    Type binaryFunction = results.CompiledAssembly.GetType("UserFunctions.BinaryFunction");
    return binaryFunction.GetMethod("Function");
}

}

在PowellMethod.css

public delegate void fcn_delegate(int n, double[] x, double[] f, int iflag);

public void dnsqe_nice(fcn_delegate fcn, int jac,  double[] x, double tol, double[,] bounds, ref double fnorm,ref  string info)
    {
// code .. 
}

我尝试了两种(测试或更好的功能)。 什么是System.Delegate,为什么它与PowellMethod中的委托定义不同?

请帮助..

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案

解决方案是

PowellMethod.fcn_delegate betterFunction = (PowellMethod.fcn_delegate)Delegate.CreateDelegate(typeof(PowellMethod.fcn_delegate), function);

并且工作正常