C#: 通過動態編譯獲取字符串所表達的值
2024-07-21 02:18:26
供稿:網友
看到許多人經常問到這個問題: 怎么由字符串 “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