zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }
  • 相关阅读:
    不用google 是不行的
    一些主题
    腾讯cdc空间
    断言assert的使用
    malloc()和free()的相关知识
    linux上面的sz,rz命令与ssh的配合
    寻找第k小的元素
    c语言中字符串处理函数
    详解之#ifdef和#ifndef
    搭建测试环境linux静态链接库与动态链接库的区别及动态库的创建
  • 原文地址:https://www.cnblogs.com/pnljs/p/3621405.html
Copyright © 2011-2022 走看看