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