C#: 通过动态编译获取字符串所表达的值

80酷酷网    80kuku.com

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



分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: