Copy codeThe Code is as follows: using System;
Using System. Data;
Using System. Configuration;
Using System. Text;
Using System. CodeDom. Compiler;
Using Microsoft. CSharp;
Using System. Reflection;
Namespace EvalGuy
{
/// <Summary>
/// This class is used to convert strings into executable text and execute
/// Copy from another place. Do not change it at will!
/// </Summary>
Public class Evaluator
{
# Region Constructor
/// <Summary>
/// Executable string Constructor
/// </Summary>
/// <Param name = "items">
/// Executable String Array
/// </Param>
Public Evaluator (EvaluatorItem [] items)
{
ConstructEvaluator (items); // call the string constructor for parsing
}
/// <Summary>
/// Executable string Constructor
/// </Summary>
/// <Param name = "returnType"> return value type </param>
/// <Param name = "expression"> execution expression </param>
/// <Param name = "name"> execution string name </param>
Public Evaluator (Type returnType, string expression, string name)
{
// Create an executable String Array
EvaluatorItem [] items = {new EvaluatorItem (returnType, expression, name )};
ConstructEvaluator (items); // call the string constructor for parsing
}
/// <Summary>
/// Executable string Constructor
/// </Summary>
/// <Param name = "item"> executable string </param>
Public Evaluator (EvaluatorItem item)
{
EvaluatorItem [] items = {item}; // convert the executable string item into an executable string item Array
ConstructEvaluator (items); // call the string constructor for parsing
}
/// <Summary>
/// Parse string Constructor
/// </Summary>
/// <Param name = "items"> string array to be parsed </param>
Private void ConstructEvaluator (EvaluatorItem [] items)
{
// Create a C # compiler instance
ICodeCompiler comp = (new CSharpCodeProvider (). CreateCompiler ());
// Compiler input parameters
CompilerParameters cp = new CompilerParameters ();
Cp. ReferencedAssemblies. Add ("system. dll"); // Add a reference to the assembly system. dll.
Cp. ReferencedAssemblies. Add ("system. data. dll"); // Add a reference to the assembly system. data. dll.
Cp. ReferencedAssemblies. Add ("system. xml. dll"); // Add a reference to the assembly system. xml. dll.
Cp. GenerateExecutable = false; // do not generate an executable file
Cp. GenerateInMemory = true; // run in memory
StringBuilder code = new StringBuilder (); // create a code string
/*
* Add common and required reference strings
*/
Code. Append ("using System;/n ");
Code. Append ("using System. Data;/n ");
Code. Append ("using System. Data. SqlClient;/n ");
Code. Append ("using System. Data. OleDb;/n ");
Code. Append ("using System. Xml;/n ");
Code. Append ("namespace EvalGuy {/n"); // The namespace for generating code is EvalGuy, just like this code.
Code. Append ("public class _ Evaluator {/n"); // generate the _ Evaluator class, where all executable code runs
Foreach (EvaluatorItem item in items) // traverses each executable string item
{
Code. AppendFormat ("public {0} {1} ()", // Add code for defining public functions
Item. ReturnType. Name, // the return value of the function is the return value type defined in the execution string.
Item. Name); // The function Name is the Name of the execution string defined in the execution string.
Code. Append ("{"); // Add function start brackets
Code. AppendFormat ("return ({0});", item. Expression); // Add the function body to return the value of the Expression defined in the executable string
Code. Append ("}/n"); // Add function ending brackets
}
Code. Append ("}"); // Add end class and end namespace brackets
// Get the result returned by the compiler instance
CompilerResults cr = comp. CompileAssemblyFromSource (cp, code. ToString ());
If (cr. Errors. HasErrors) // if an error occurs
{
StringBuilder error = new StringBuilder (); // create an error message string
Error. Append ("compiled expression with error:"); // Add error text
Foreach (CompilerError err in cr. Errors) // traverses each compilation Error
{
Error. AppendFormat ("{0}/n", err. ErrorText); // Add the error text with a line break after each error
}
Throw new Exception ("Compilation error:" + error. ToString (); // throw an Exception
}
Assembly a = cr. CompiledAssembly; // gets the Assembly of the compiler instance
_ Compiled = a. CreateInstance ("EvalGuy. _ Evaluator"); // find and declare the EvalGuy. _ Evaluator instance through the Assembly
}
# Endregion
# Region Public Member
/// <Summary>
/// Execute the string and return the integer value
/// </Summary>
/// <Param name = "name"> execution string name </param>
/// <Returns> execution result </returns>
Public int EvaluateInt (string name)
{
Return (int) Evaluate (name );
}
/// <Summary>
/// Execute the string and return the string value
/// </Summary>
/// <Param name = "name"> execution string name </param>
/// <Returns> execution result </returns>
Public string EvaluateString (string name)
{
Return (string) Evaluate (name );
}
/// <Summary>
/// Execute the string and return a Boolean Value
/// </Summary>
/// <Param name = "name"> execution string name </param>
/// <Returns> execution result </returns>
Public bool EvaluateBool (string name)
{
Return (bool) Evaluate (name );
}
/// <Summary>
/// Execute the string and return the object Value
/// </Summary>
/// <Param name = "name"> execution string name </param>
/// <Returns> execution result </returns>
Public object Evaluate (string name)
{
MethodInfo mi = _ Compiled. GetType (). GetMethod (name); // gets a reference to a method named name in the type of _ Compiled
Return mi. Invoke (_ Compiled, null); // execute the method referenced by mi
}
# Endregion
# Region static member
/// <Summary>
/// Execute the expression and return the integer value
/// </Summary>
/// <Param name = "code"> expression to be executed </param>
/// <Returns> calculation result </returns>
Static public int EvaluateToInteger (string code)
{
Evaluator eval = new Evaluator (typeof (int), code, staticMethodName); // generates the Evaluator Class Object
Return (int) eval. Evaluate (staticMethodName); // execute and return Integer Data
}
/// <Summary>
/// Execute the expression and return a string value
/// </Summary>
/// <Param name = "code"> expression to be executed </param>
/// <Returns> calculation result </returns>
Static public string EvaluateToString (string code)
{
Evaluator eval = new Evaluator (typeof (string), code, staticMethodName); // generates the Evaluator Class Object
Return (string) eval. Evaluate (staticMethodName); // execute and return string-type data
}
/// <Summary>
/// Execute the expression and return a Boolean Value
/// </Summary>
/// <Param name = "code"> expression to be executed </param>
/// <Returns> calculation result </returns>
Static public bool EvaluateToBool (string code)
{
Evaluator eval = new Evaluator (typeof (bool), code, staticMethodName); // generates the Evaluator Class Object
Return (bool) eval. Evaluate (staticMethodName); // execute and return boolean data
}
/// <Summary>
/// Execute the expression and return the object type value
/// </Summary>
/// <Param name = "code"> expression to be executed </param>
/// <Returns> calculation result </returns>
Static public object EvaluateToObject (string code)
{
Evaluator eval = new Evaluator (typeof (object), code, staticMethodName); // generates the Evaluator Class object
Return eval. Evaluate (staticMethodName); // execute and return object-type data
}
# Endregion
# Region private member
/// <Summary>
/// The execution string name of the Static Method
/// </Summary>
Private const string staticMethodName = "_ foo ";
/// <Summary>
/// Used to dynamically reference the generated class and execute the executable string contained in it
/// </Summary>
Object _ Compiled = null;
# Endregion
}
/// <Summary>
/// Executable string (that is, an executable string)
/// </Summary>
Public class EvaluatorItem
{
/// <Summary>
/// Return Value Type
/// </Summary>
Public Type ReturnType;
/// <Summary>
/// Execution expression
/// </Summary>
Public string Expression;
/// <Summary>
/// Execution string name
/// </Summary>
Public string Name;
/// <Summary>
/// Executable string Constructor
/// </Summary>
/// <Param name = "returnType"> return value type </param>
/// <Param name = "expression"> execution expression </param>
/// <Param name = "name"> execution string name </param>
Public EvaluatorItem (Type returnType, string expression, string name)
{
ReturnType = returnType;
Expression = expression;
Name = name;
}
}
}