C #: Get the value expressed by the string by dynamic compilation

Source: Internet
Author: User
Tags eval
compiling | dynamic | Strings See a lot of people often ask this question: How to String "126 + (256-2^4)", or How to judge "> 56 | | 14<45 "Results etc, checked on MSDN, wrote an eval class

/*****************************************************************
* * FileName: Eval.cs
* * Copyright (c) 1999-2003
* * Creator: Phoenix
* * Date Created:
* * Modified Person:
* * Modified Date:
* * Description: Gets the logical meaning represented by the string
* * Version: 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);
}
}

------------------------------------------------------------------------

Call:

Console.WriteLine (Eval.getvalue ("125-23"));
Console.WriteLine (Eval.getvalue ("125<23"));

Output:
102
False





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.