您的位置:首页 > 编程语言 > C#

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: