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;
            }
        }
    }
  • 相关阅读:
    JSON
    robotframework常见的问题
    robotframework——excel处理方法
    robotframework获得随机数字的方法
    robotframework定位动态元素
    robotframework的关键字区分大小写的问题
    自动化测试相关知识
    ride控制台乱码的解决方法
    xpath定位兄弟元素
    python——运算
  • 原文地址:https://www.cnblogs.com/pnljs/p/3621405.html
Copyright © 2011-2022 走看看