Dynamic execution of C # code

Source: Internet
Author: User
Tags parse string

Using System;

Using System.CodeDom.Compiler;
Using System.Collections.Generic;
Using System.Linq;
Using System.Reflection;
Using System.Text;
Using System.Threading.Tasks;

Namespace Evaluator.core
{
public class Evaluator
{
#region Constructors

<summary>
Constructors for executable strings
</summary>
<param name= "Items" >
An array of executable strings
</param>
Public Evaluator (evaluatoritem[] items)
{
Constructevaluator (items); Call parse string constructor for parsing
}

<summary>
Constructors for executable strings
</summary>
<param name= "ReturnType" > Return value type </param>
<param name= "expression" > Execute expression </param>
<param name= "Name" > Execute string name </param>
Public Evaluator (Type returntype, string expression, string name)
{
Creating an array of executable strings
evaluatoritem[] items = {New Evaluatoritem (returntype, expression, name)};
Constructevaluator (items); Call parse string constructor for parsing
}

<summary>
Constructors for executable strings
</summary>
<param name= "Item" > Executable string entry </param>
Public Evaluator (Evaluatoritem item)
{
evaluatoritem[] items = {Item};//to convert an executable string entry into an array of executable string items
Constructevaluator (items); Call parse string constructor for parsing
}

<summary>
Parsing string Constructors
</summary>
<param name= "Items" > Array of strings to parse </param>
private void Constructevaluator (evaluatoritem[] items)
{
Creating a C # compiler instance
CodeDomProvider Provider = Codedomprovider.createprovider ("C #");

It's outdated.
ICodeCompiler Comp = provider. CreateCompiler ();

Compiler passed in parameters
CompilerParameters cp = new CompilerParameters ();
Cp. Referencedassemblies.add ("System.dll"); To add a reference to an assembly System.dll
Cp. Referencedassemblies.add ("System.Data.dll"); To add a reference to an assembly System.Data.dll
Cp. Referencedassemblies.add ("System.Xml.dll"); To add a reference to an assembly System.Xml.dll
Cp. Referencedassemblies.add ("System.Core.dll"); To add a reference to an assembly System.Core.dll
Cp. GenerateExecutable = false; Do not generate executable files
Cp. GenerateInMemory = true; Running in memory

StringBuilder code = new StringBuilder (); Creating a code string
/*
* Add common and mandatory reference strings
*/
Code. Append ("Using System;");
Code. Append ("Using System.Data;");
Code. Append ("Using System.Data.SqlClient;");
Code. Append ("Using System.Data.OleDb;");
Code. Append ("Using System.Xml;");
Code. Append ("Using System.Collections.Generic;");

Code. Append ("namespace Akmii.dynamicmath {"); The namespace of the generated code is Evalguy, as in this code

Code. Append ("public class _evaluator {"); Produces the _evaluator class, where all executable code runs in this class
foreach (Evaluatoritem item in items)//traversal of each executable string entry
{
Code. AppendFormat ("public {0} {1} ()",//Add define common function code
Item. Returntype.name,//function return value is the type of return value defined in the executable string entry
Item. Name); Function name is the execution string name defined in the executable string entry
Code. Append ("{"); Add function Start parenthesis
Code. AppendFormat ("Return ({0});", item. expression);//Add function body, return the value of the expressions defined in the executable string item
Code. Append ("}"); Add function closing parentheses
}
Code. Append ("}}"); Add class end and namespace closing parentheses

Get the return result of the compiler instance
CompilerResults CR = Provider.compileassemblyfromsource (CP, code. ToString ());//comp

if (CR. errors.haserrors)//If there is an error
{
StringBuilder error = new StringBuilder (); Create error message string
Error. Append ("compiler has the wrong expression:"); Add error text
foreach (CompilerError err in CR. Errors)//traversal of each occurrence of compilation errors
{
Error. AppendFormat ("{0}/n", err.) ErrorText); Add in error text, wrap after each error
}
throw new Exception ("Compile Error:" + error.) ToString ());//Throws an exception
}
Assembly a = cr.compiledassembly; Get the assembly for the compiler instance
_compiled = A.createinstance ("Akmii.dynamicmath._evaluator"); Finds and declares SSEC through an assembly. Examples of Math._evaluator
}

#endregion Constructors

#region Public Members

<summary>
Executes a string and returns an integral type value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
public int Evaluateint (string name)
{
return (int) Evaluate (name);
}

<summary>
Executes a string and returns a double value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
Public double evaluatedouble (string name)
{
Return (double) Evaluate (name);
}

<summary>
Executes a string and returns a long integer value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
Public long Evaluatelong (string name)
{
Return (long) Evaluate (name);
}

<summary>
Executes a string and returns a decimal value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
Public decimal Evaluatedecimal (string name)
{
Return (decimal) Evaluate (name);
}

<summary>
Executes a string and returns a string type value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
public string evaluatestring (string name)
{
Return (String) Evaluate (name);
}

<summary>
Executes a string and returns a Boolean value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
public bool Evaluatebool (string name)
{
return (BOOL) Evaluate (name);
}

<summary>
Executes a string and returns a value of type Object
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
public Object Evaluate (string name)
{
MethodInfo mi = _compiled.gettype (). GetMethod (name);//Gets a reference to the method named name in the _compiled owning type
Return MI. Invoke (_compiled, NULL); Perform the method referenced by Mi
}

#endregion Public Members

#region Static Members

<summary>
Executes an expression and returns an integer value
</summary>
<param name= "code" > Expressions to execute </param>
<returns> Operation Results </returns>
static public int Evaluatetointeger (string code)
{
Evaluator eval = new Evaluator (typeof (int), code, Staticmethodname);//Generate a pair of Evaluator classes
return (int) eval. Evaluate (Staticmethodname); Executes and returns an integral type of data
}

<summary>
Executes an expression and returns a Double value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
static public double evaluatetodouble (string code)
{
Evaluator eval = new Evaluator (typeof (Double), code, Staticmethodname);//Generate a pair of Evaluator classes
Return (double) eval. Evaluate (Staticmethodname);
}

<summary>
Executes an expression and returns a long integer value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
static public long Evaluatetolong (string code)
{
Evaluator eval = new Evaluator (typeof (Long), code, Staticmethodname);//Generate a pair of Evaluator classes
Return (long) eval. Evaluate (Staticmethodname);
}

<summary>
Executes an expression and returns a decimal value
</summary>
<param name= "Name" > Execute string name </param>
<returns> Execution Results </returns>
static public decimal Evaluatetodecimal (string code)
{
Evaluator eval = new Evaluator (typeof (decimal), code, Staticmethodname);//Generate a pair of Evaluator classes
Return (decimal) eval. Evaluate (Staticmethodname);
}

<summary>
Executes an expression and returns a String value
</summary>
<param name= "code" > Expressions to execute </param>
<returns> Operation Results </returns>
static public string evaluatetostring (string code)
{
Evaluator eval = new Evaluator (typeof (String), code, Staticmethodname);//Generate a pair of Evaluator classes
Return (string) eval. Evaluate (Staticmethodname); Executes and returns the string type data
}

<summary>
Executes an expression and returns a Boolean value
</summary>
<param name= "code" > Expressions to execute </param>
<returns> Operation Results </returns>
static public bool Evaluatetobool (string code)
{
Evaluator eval = new Evaluator (typeof (BOOL), code, Staticmethodname);//Generate a pair of Evaluator classes
return (BOOL) eval. Evaluate (Staticmethodname); Executes and returns a Boolean type of data
}

<summary>
Executes an expression and returns an object type value
</summary>
<param name= "code" > Expressions to execute </param>
<returns> Operation Results </returns>
Static public Object Evaluatetoobject (string code)
{
Evaluator eval = new Evaluator (typeof (object), code, Staticmethodname);//Generate a pair of Evaluator classes
Return eval. Evaluate (Staticmethodname); Executes and returns the object type data
}

#endregion Static Members

#region Private Members

<summary>
Execution string name of static method
</summary>
Private Const string staticmethodname = "__foo";

<summary>
The class used to dynamically reference the build, executing its inner executable string
</summary>
Private object _compiled = null;

#endregion Private Members
}

public class Evaluatoritem
{
<summary>
return value type
</summary>
Public Type ReturnType;

<summary>
Executing an expression
</summary>
public string Expression;

<summary>
Execute string Name
</summary>
public string Name;

<summary>
Executable String Entry constructors
</summary>
<param name= "ReturnType" > Return value type </param>
<param name= "expression" > Execute expression </param>
<param name= "Name" > Execute string name </param>
Public Evaluatoritem (Type returntype, string expression, string name)
{
ReturnType = ReturnType;
expression = expression;
name = name;
}
}
}

Dynamic execution of C # code

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.