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