|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.JScript;
namespace ClassLibrary1
{ public class Evaluator
{
private static Type _evaluatorType = null;
private static readonly string _jscriptSource =
@"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}
}";
static Evaluator()
{
ICodeCompiler compiler;
compiler = new JScriptCodeProvider().CreateCompiler();
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results;
results = compiler.CompileAssemblyFromSource(parameters,
_jscriptSource);
Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator.Evaluator");
}
// ...
public static bool EvalToBoolean(string statement)
{
string s = EvalToString(statement);
return bool.Parse(s);
}
public static string EvalToString(string statement)
{
object o = EvalToObject(statement);
return o.ToString();
}
public static object EvalToObject(string statement)
{
object evaluator = Activator.CreateInstance(_evaluatorType);
return _evaluatorType.InvokeMember("Eval",
BindingFlags.InvokeMethod, null, evaluator, new object[]
{ statement } );
}
public static void Main(string[] arge)
{
EvalToBoolean("1 == 1");
Console.WriteLine(EvalToBoolean("1 == 1"));
////
// Lot lot = new Lot("Lot1");
// Console.WriteLine(lot.ID);
// Console.WriteLine(lot.AMOUNT );
// Console.WriteLine(lot.getTotal() );
//dynamic
string script = @" var yield =100;
if (Lot.getCurrentYield() <90 ) {
yield = 90;
}
return yield;
";
Type visualStudioType = Type.GetType("ClassLibrary1.Lot");
Object[] lotid = {"Lot15"};
dynamic dte = Activator.CreateInstance(visualStudioType, lotid);
Console.WriteLine("========================================");
Console.WriteLine(dte.ID);
Console.WriteLine(dte.AMOUNT);
Console.WriteLine(dte.getCurrentYield());
//
Type visualStudioType2 = Type.GetType("ClassLibrary1.Eqp");
Object[] eqpid = { "EP1" };
dynamic dte2 = Activator.CreateInstance(visualStudioType2, eqpid);
Console.WriteLine("========================================");
Console.WriteLine(dte2.ID);
Console.WriteLine(dte2.getCapacity());
Console.Read();
}
}
} |
|