通過動態編譯擷取字串表達的值

來源:互聯網
上載者:User
看到許多人經常問到這個問題: 怎麼由字串 “126 + (256 - 2^4 )”,或者怎麼判斷 “115 > 56 || 14<45”的結果等等,在MSDN上查了查,寫了一個Eval類

 /*****************************************************************
** 檔案名稱:       Eval.cs
** Copyright (c) 1999 -2003
** 建立人:       Phoenix
** 建立日期:
** 修改人:
** 修改日期:
** 描 述:         擷取字串所表示的邏輯意義
** 版 本:1.0
******************************************************************/
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

public class Eval
{
static object GetValue( string value )
 {
   string codeSnippet = "using System; " + "\r\n" +
                                   "namespace CzG {" + "\r\n" +
                                               " public class Eval" + "\r\n" +
                                               " {" + "\r\n" +
                                   "       public Eval(){} " + "\r\n" +
                                               "  public object GetValue()" + "\r\n" +
                                               "  {" + "\r\n" +
                                               "   return " + value + ";" + "\r\n" +
                                               "  }" + "\r\n" +
                                               " } }";
 

   CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit( codeSnippet );
 
   ICodeCompiler compiler =  new CSharpCodeProvider().CreateCompiler();
   CompilerParameters para = new CompilerParameters();
   para.ReferencedAssemblies.Add( "System.dll" );
   para.GenerateInMemory = true;
   para.GenerateExecutable = false;
   para.OutputAssembly = "Eval.dll";
  
   Assembly asm = compiler.CompileAssemblyFromDom( para , unit ).CompiledAssembly;
  
   Type type = asm.GetType( "CzG.Eval" );
   MethodInfo mi = type.GetMethod( "GetValue" , BindingFlags.Public | BindingFlags.Instance ); 
  
   object obj = asm.CreateInstance( "CzG.Eval" );
   return mi.Invoke( obj , null );
  }
}

----------------------------------

調用:

Console.WriteLine( Eval.GetValue(“125 -23” ) );
Console.WriteLine( Eval.GetValue(“125<23“ ) );

Output:
102
False



相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。