1
我想寫微分方程求解器,我需要允許用戶通過文本框輸入它們。問題在於當方程只包含x或x + y時,求解方法會改變。 Ifound上http://www.codeproject.com/KB/recipes/matheval.aspx偉大的代碼,但我有它延伸到2種方法使用CodeDom評估表達式
using System;
using System.Collections;
using System.Reflection;
namespace RKF45{
public class MathExpressionParser
{
public object myobj = null;
public ArrayList errorMessages;
public MathExpressionParser()
{
errorMessages = new ArrayList();
}
public bool init(string expr)
{
Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
cpar.GenerateInMemory = true;
cpar.GenerateExecutable = false;
string src;
cpar.ReferencedAssemblies.Add("system.dll");
src = "using System;" +
"class myclass " +
"{ " +
"public myclass(){} " +
"public static double eval(double x) " +
"{ " +
"return " + expr + "; " +
"} " +
"public static double eval2(double x,double y) " +
"{ " +
"return " + expr + "; " +
"} " +
"} ";
System.CodeDom.Compiler.CompilerResults cr = cp.CompileAssemblyFromSource(cpar, src);
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
errorMessages.Add(ce.ErrorText);
if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
{
Type ObjType = cr.CompiledAssembly.GetType("myclass");
try
{
if (ObjType != null)
{
myobj = Activator.CreateInstance(ObjType);
}
}
catch (Exception ex)
{
errorMessages.Add(ex.Message);
}
return true;
}
else
return false;
}
public double eval(double x)
{
double val = 0.0;
Object[] myParams = new Object[1] { x };
if (myobj != null)
{
System.Reflection.MethodInfo evalMethod = myobj.GetType().GetMethod("eval");
val = (double)evalMethod.Invoke(myobj, myParams);
}
return val;
}
public double eval2(double x, double y)
{
double val = 0.0;
Object[] myParams = new Object[2] { x, y };
if (myobj != null)
{
System.Reflection.MethodInfo evalMethod = myobj.GetType().GetMethod("eval2");
val = (double)evalMethod.Invoke(myobj, myParams);
}
return val;
}
}
}
任何想法麻煩,爲什麼EVAL2方法不工作correclty當我給像X + Y的表達? eval工作正常,但我需要其中的2個來解決在文本框中輸入的不同方程式。
好吧,我用2個參數做了eval的鏡像類,現在它的工作。感謝您的回覆:) –
考慮upvoting和標記答案爲接受,如果它真的幫助你;) –