This is a simple class library (or just .cs file if you wish) to allow for
runtime compilation and evaluation of C# code blocks. There are both
static methods of the Evaluator
class that allow for simple
use (but at a performance penalty) or you can use the object directly to create
multiple evaluations:
How does it work? I am using the CodeDOM to create a simple assembly
with a single class in it. I simply transform each of the EvaluatorItem
s
into a method of the class. When you call EvaluateInt()
or Evaluate()
, I use reflection to get a MethodInfo
object
and call the method.
The source code comes packaged in a Class Library with a Test program that you can use to get examples of use:
To compile the expressions, I am creating a new CSharpCodeProvider
and setting
Compiler attributes (like adding references, telling it to generate it in
memory, etc.). Then I am building a dummy class that I can append my
methods on. Lastly I compile it (check for errors) and save the object to
use to call with the MethodInfo
structure:
When I call the _Compiled
object, I use a MethodInfo
object to
Invoke the call and return the result to the user:
(轉自:http://www.codeproject.com/KB/cs/runtime_eval.aspx)