C# 调用动态代码
2014-03-24 17:35
78 查看
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.CSharp; using System.CodeDom.Compiler; namespace WindowsFormsApplication1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private bool CalculateExpression(string expression) { string source = GetSource(expression); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameter = new CompilerParameters(); parameter.ReferencedAssemblies.Add("System.dll"); parameter.GenerateExecutable = false; parameter.GenerateInMemory = true; CompilerResults result = provider.CompileAssemblyFromSource(parameter, source); if (result.Errors.Count > 0) { throw new Exception("表达式运行不成功,请验证表达式是否合法!"); } else { return (bool)result.CompiledAssembly.GetType("Calc.CalcExpressionHelper").GetMethod("CalcExpression").Invoke(null, null); } } private string GetSource(string expression) { string source = "using System; " + "namespace Calc " + "{ " + "public static class CalcExpressionHelper " + "{ " + "public static bool CalcExpression() " + "{ " + "return " + expression + ";" + "} " + "} " + "}"; return source; } } }
相关文章推荐
- 非常不错的C#动态调用DLL代码
- 非常不错的C#动态调用DLL代码
- 非常不错的C#动态调用DLL代码
- C#用反射将Model类动态载入表单 利用Velocity传值 调用只需一句代码
- 【经典实例】利用C#反射动态编译代码,创建类的实例,并调用其成员
- *****C# 程序代码动态修改Label值(对Windows窗体控件进行线程安全调用)
- C#程序实现动态调用DLL的研究 (入门附代码)
- C# .Net动态调用webService实现思路及代码
- C# .Net动态调用webService实现思路及代码
- C#后台动态调用样式表文件的代码
- C++调用托管C#代码设置(vs2008)
- c# 动态加载dll文件,并实现调用其中的简单方法
- C#代码与javaScript函数的相互调用
- C#Winform基础 一个button按钮调用另外一个button按钮的代码
- C++工程代码打包的dll在C#工程上使用注意点!变量对应关系与dll调用出错情况。
- C# 动态代码执行
- C++通过DLL调用C#代码
- C# 动态调用WebService
- C#代码与javaScript函数的相互调用