C# 调用动态代码

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;
        }
    }
}
原文地址:https://www.cnblogs.com/pnljs/p/3621405.html