Use the C # dynamic compilation function to implement the Eval function like Javascript to perform mathematical operations on a string.

Source: Internet
Author: User

Because one function in the project is to input a calculated expression by the user.

For example, the Order points calculation expression: "{0} * 1.5 + 50" points = order amount * 1.5 times + 50 points

So how does my program calculate the result? For example, the current amount is 100.

The expression is "100*1.5 + 50 ";

Good test code

 

Code

 Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. CodeDom;
Using System. CodeDom. Compiler;
Using Microsoft. CSharp;
Using System. Reflection;
Using System. Globalization;


Namespace Z. Shop. Test. AutoCompiler
{
[NUnit. Framework. TestFixture]
Public class Test1
{
[NUnit. Framework. TestFixtureSetUp]
Public void SetUp ()
{
Log4net. config. xmlconfigurator. Configure (new system. Io. fileinfo ("log4net. cfg. xml "));
}

Public double eval (string expression)
{
Csharpcodeprovider objcsharpcodeprivoder = new csharpcodeprovider ();
Icodecompiler objicodecompiler = objcsharpcodeprivoder. createcompiler ();
Compilerparameters objcompilerparameters = new compilerparameters ();
Objcompilerparameters. referencedassemblies. Add ("system. dll ");
Objcompilerparameters. generateexecutable = false;
Objcompilerparameters. generateinmemory = true;
// Here is the generated dynamic code
Stringbuilder sb = new stringbuilder ();
SB. append ("using system ;");
SB. append (environment. newline );
Sb. Append ("namespace DynamicCodeGenerate ");
Sb. Append (Environment. NewLine );
Sb. Append ("{");
Sb. Append (Environment. NewLine );
Sb. Append ("public class DynamicCodeEval ");
Sb. Append (Environment. NewLine );
Sb. Append ("{");
Sb. Append (Environment. NewLine );
Sb. Append ("public object Eval ()");
Sb. Append (Environment. NewLine );
Sb. Append ("{");
Sb. Append (Environment. NewLine );
Sb. Append ("return" + expression + ";"); // It is actually a simple expression. You can modify it according to your own situation if you want to make it complex.
Sb. Append (Environment. NewLine );
Sb. Append ("}");
SB. append (environment. newline );
SB. append ("}");
SB. append (environment. newline );
SB. append ("}");

String code = sb. tostring ();

Compilerresults Cr = objicodecompiler. compileassemblyfromsource (objcompilerparameters, Code );
// Reflection is returned.
Assembly objassembly = Cr. compiledassembly;
Object objdynamiccodeeval = objassembly. createinstance ("dynamiccodegenerate. dynamiccodeeval ");
Methodinfo objmi = objdynamiccodeeval. GetType (). getmethod ("eval ");
VaR result = convert. todouble (objmi. Invoke (objdynamiccodeeval, null ));
Return result;
}

[Nunit. Framework. Test]
Public void T1 ()
{
Var result = evals ("100*1.5 + 50 ");
Console. Write (result. ToString ());
}
}
}

 

 

Execution result:200

 

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.