首页 > 编程语言 >C#动态编译计算

C#动态编译计算

时间:2023-07-13 15:44:35浏览次数:39  
标签:string C# expression double 编译 using new 动态 Expression

示例代码:

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;

namespace ConsoleApp6
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Expression e = new Expression("x+5*9/3.2+6");
            Console.WriteLine(e.Compute(10));
            Console.Read();
        }
    }

    public class Expression
    {
        private object instance;
        private MethodInfo method;

        /// <summary>
        /// 表达试运算
        /// </summary>
        /// <param name="expression">表达试</param>
        public Expression(string expression)
        {
            if (expression.IndexOf("return") < 0)
            {
                expression = "return " + expression + ";";
            }

            string className = "Expression";
            string methodName = "Compute";
            CompilerParameters p = new CompilerParameters();
            p.GenerateInMemory = true;
            var source = string.Format("using System;sealed class {0}{{public double {1}(double x){{{2}}}}}", className, methodName, expression);
            CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, source);
            if (cr.Errors.Count > 0)
            {
                string msg = "Expression(\"" + expression + "\"): \n";
                foreach (CompilerError err in cr.Errors)
                {
                    msg += err.ToString() + "\n";
                }
                throw new Exception(msg);
            }
            instance = cr.CompiledAssembly.CreateInstance(className);
            method = instance.GetType().GetMethod(methodName);
        }

        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="x"></param>
        /// <returns>返回计算值</returns>
        public double Compute(double x)
        {
            return (double)method.Invoke(instance, new object[] { x });
        }
    }
}

 

标签:string,C#,expression,double,编译,using,new,动态,Expression
From: https://www.cnblogs.com/wzwyc/p/17551079.html

相关文章

  • 验证torch和torchvision安装成功
    importtorchprint("torch_version:",torch.__version__)print("cuda_version:",torch.version.cuda)print("cudnn_version:",torch.backends.cudnn.version())print("----------------------------------")flag=torch.cuda.is_ava......
  • 【Netty】「优化进阶」(二)浅谈 LengthFieldBasedFrameDecoder:如何实现可靠的消息分割?
    前言本篇博文是《从0到1学习Netty》中进阶系列的第二篇博文,主要内容是通过不同的应用案例来了解LengthFieldBasedFrameDecoder是如何处理不同的消息,实现自动分割,往期系列文章请访问博主的Netty专栏,博文中的所有代码全部收集在博主的GitHub仓库中;介绍LengthFieldBasedFrameDe......
  • C#使用泛型方法将Datatable转换成List对象集合
     在项目中遇到需要将Datatable转换成对象的需求,通过dr[0]取下标这种获取,如果数据的顺序发生了改变则需要改变全部,工作量大foreach(DataRowdrindt.Rows){CheckDetailinfo=newCheckDetail();info.org_id=dr[0].ToStrin......
  • 【Azure App Service】Web Job 报错 UNC paths are not supported. Defaulting to Win
    问题描述PHP的WebJob,通过artisan来配置路径启动PHP任务,相关启动脚本如下:artisan_path="d:\\home\\site\\wwwroot";cd${artisan_path}echo"\n"pwdphpartisanschedule:run但是,在运行的时候遇见报错:[07/06/202301:57:31>0f21a2:INFO]/d/home/site/wwwroo......
  • 发送请求忘记指定协议方式,日志com.jcraft.jsch.JSchException: java.net.ConnectExcep
      2023-07-1319:06:51.487-ERROR17629---[http-nio-192.168.2.206-36093-exec-8]c.t.b.p.b.c.common.util.sftp.SftpPool:com.jcraft.jsch.JSchException:java.net.ConnectException:拒绝连接(Connectionrefused)_atcom.jcraft.jsch.Util.createSocket(......
  • 处理.git文件夹过大出现臃肿问题-filter-branch和BFG工具
    Git开发手册git一些不常用的命令记不住,可以查看git开发手册(https://m.php.cn/manual/view/34957.html)1、.git/objects/pack文件过大今天从git拉取项目进行开发的时候克隆的很慢,还以为是网速的问题。查看了一些git命令框的拉取网络速度发现网速也很快,克隆下来后才发现是.git文......
  • Batch、Drawcall和SetPassCall
    转自:DrawCall,Batches,SetPasscalls是什么?原理?【匠】-知乎(zhihu.com)cube使用双passshader:  cube使用同材质,同shader,不勾选static:完全不合批,batch:基础的2个batch+6个cube*2个pass,setpasscall:基础的2个batch+6个cube*2个pass   cube使用同材质,同shader,勾选st......
  • StarRocks Segment源码阅读笔记--SegmentIterator创建
    StarRocks中要读取Segment中的数据,需要先创建SegmentIteratorStatusOr<ChunkIteratorPtr>Segment::_new_iterator(constSchema&schema,constSegmentReadOptions&read_options){DCHECK(read_options.stats!=nullptr);//tryingtoprunethecurrentse......
  • Capture One 23-RAW图像编辑软件mac/win版
    CaptureOne23是一款专业的RAW图像编辑软件,广泛应用于摄影行业。它提供了丰富而强大的工具和功能,帮助摄影师优化、处理和管理他们的原始图像。→→↓↓载CaptureOne23mac/win版  RAW文件支持:CaptureOne23支持超过500种不同相机的原始RAW文件,包括主流相机品牌如佳能......
  • office学习笔记
    目录Excel函数使用VLOOKUP制作四象限图wordPowerPointExcel函数使用VLOOKUP使用说明:https://support.microsoft.com/zh-cn/office/vlookup-函数-0bbc8083-26fe-4963-8ab8-93a18ad188a1功能:需要在表格或区域中按行查找内容时,请使用VLOOKUP。说明:在这一最简单的形式中,VLOOK......