日期:2011-08-06  浏览次数:20881 次

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