• 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;
            }
        }
    }
  • 相关阅读:
    代码编辑
    作业7
    实验 13 综合练习三
    模版 实验二 概要设计
    在线评测系统(OJ)使用方法
    作业 6 结构体
    结构体简介
    实验 10 指针2
    (第一周)软件工程四人组
    (第一周)读《构建之法》
  • 原文地址:https://www.cnblogs.com/pnljs/p/3621405.html
Copyright © 2020-2023  润新知