服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

通过动态编译获取字符串表达的值


  看到许多人经常问到这个问题: 怎么由字符串 “126 + (256 - 2^4 )”,或者怎么判断 “115 > 56 || 14<45”的结果等等,在msdn上查了查,写了一个eval类看到许多人经常问到这个问题: 怎么由字符串 “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

扫描关注微信公众号