2011-11-26 52 views
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個來解決在文本框中輸入的不同方程式。

回答

1

您不能在eval(double x)eval(double x, double y)方法中使用包含兩個不同變量(如「x」和「y」)的表達式:第一個方法不會編譯(因爲第二個變量沒有在那裏定義),而在兩種情況下使用僅包含單個變量的表達式(如「x」)編譯。這就解釋了爲什麼在兩個變量的情況下你不能調用eval2()

+0

好吧,我用2個參數做了eval的鏡像類,現在它的工作。感謝您的回覆:) –

+0

考慮upvoting和標記答案爲接受,如果它真的幫助你;) –