会员
众包
新闻
博问
闪存
赞助商
HarmonyOS
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
IDEA1 STUDIO.net
Be Patient!
博客园
首页
新随笔
联系
订阅
管理
公告
计算类
Posted on
2007-01-18 17:14
Leon0812
阅读(
300
) 评论(
0
)
收藏
举报
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.CodeDom.Compiler;
using
System.Reflection;
using
Microsoft.CSharp;
namespace
YYC
{
/**/
/**/
/**/
///
<summary>
///
计算表达式的类
///
</summary>
public
class
CalculateExpression
{
/**/
/**/
/**/
///
<summary>
///
接受一个string类型的表达式并计算结果,返回一个object对象,静态方法
///
</summary>
///
<param name="expression"></param>
///
<returns></returns>
public
static
object
Calculate(
string
expression)
{
string
className
=
"
Calc
"
;
string
methodName
=
"
Run
"
;
expression
=
expression.Replace(
"
/
"
,
"
*1.0/
"
);
//
创建编译器实例。
CodeDomProvider complier
=
(
new
Microsoft.CSharp.CSharpCodeProvider());
//
设置编译参数。
CompilerParameters paras
=
new
CompilerParameters();
paras.GenerateExecutable
=
false
;
paras.GenerateInMemory
=
true
;
//
创建动态代码。
StringBuilder classSource
=
new
StringBuilder();
classSource.Append(
"
public class
"
+
className
+
"
\n
"
);
classSource.Append(
"
{\n
"
);
classSource.Append(
"
public object
"
+
methodName
+
"
()\n
"
);
classSource.Append(
"
{\n
"
);
classSource.Append(
"
"
+
expression
+
"
\n
"
);
classSource.Append(
"
return feeResult;\n
"
);
classSource.Append(
"
}\n
"
);
classSource.Append(
"
}
"
);
//
编译代码。
CompilerResults result
=
complier.CompileAssemblyFromSource(paras, classSource.ToString());
//
获取编译后的程序集。
Assembly assembly
=
result.CompiledAssembly;
//
动态调用方法。
object
eval
=
assembly.CreateInstance(className);
MethodInfo method
=
eval.GetType().GetMethod(methodName);
object
reobj
=
method.Invoke(eval,
null
);
GC.Collect();
return
reobj;
}
}
}
刷新页面
返回顶部
博客园
© 2004-2025
浙公网安备 33010602011771号
浙ICP备2021040463号-3