欢迎光临
我们一直在努力

C#: 通过动态编译获取字符串所表达的值-.NET教程,C#语言

建站超值云服务器,限时71元/月

看到许多人经常问到这个问题: 怎么由字符串 “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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » C#: 通过动态编译获取字符串所表达的值-.NET教程,C#语言
分享到: 更多 (0)