01.
using
System;
02.
using
System.Reflection;
03.
using
System.CodeDom.Compiler;
04.
using
System.Text;
05.
using
Microsoft.CSharp;
06.
07.
namespace
CSharpMath
08.
{
09.
class
Calculator
10.
{
11.
public
static
double
EvaluateExpression(
string
expression)
12.
{
13.
StringBuilder Sb =
new
StringBuilder();
14.
Sb.AppendLine(
"public static class Cal"
);
15.
Sb.AppendLine(
"{"
);
16.
Sb.AppendLine(
"\t public static double cal()"
);
17.
Sb.AppendLine(
"\t {"
);
18.
Sb.AppendFormat(
"\t\t return {0};"
, expression);
19.
Sb.AppendLine(
"\t }"
);
20.
Sb.AppendLine(
"}"
);
21.
22.
string
code = Sb.ToString();
23.
CompilerResults compilerResults = CompileScript(code);
24.
25.
if
(compilerResults.Errors.HasErrors)
26.
{
27.
throw
new
InvalidOperationException(
"Expression has a syntax error."
);
28.
}
29.
30.
31.
Assembly assembly = compilerResults.CompiledAssembly;
32.
MethodInfo method = assembly.GetType(
"Cal"
).GetMethod(
"cal"
);
33.
34.
return
(
double
)method.Invoke(
null
,
null
);
35.
}
36.
37.
38.
private
static
CompilerResults CompileScript(
string
source)
39.
{
40.
CompilerParameters parms =
new
CompilerParameters();
41.
42.
parms.GenerateExecutable =
false
;
43.
parms.GenerateInMemory =
true
;
44.
parms.IncludeDebugInformation =
false
;
45.
46.
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider(
"CSharp"
);
47.
48.
return
compiler.CompileAssemblyFromSource(parms, source);
49.
}
50.
}
51.
}