0
我試圖在運行時向一個類提供編譯的C#函數。C#無法將`System.Delegate'表達式轉換爲`PowellMethod.fcn_delegate'
我得到以下錯誤: 參數#1' cannot convert
System.Delegate '表達鍵入`PowellMethod.fcn_delegate'
在主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 ..
}
我試過(t est或更好的功能)。 什麼是這個System.Delegate,它爲什麼不同於PowellMethod中的委託定義?
請幫助..