• netcore 下的 C# 表达式求值


    netframework 下的 codedom 代码已经不能用了,会报错,改用Roslyn来写:

    先安装包

    install-package Microsoft.CodeAnalysis.CSharp

    核心代码,尝试了好久

    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    public class CsEvaluator
    {
            /// <summary>CSharp 表达式求值</summary>
            /// <param name="expression">CSharp 表达式。如:2.5, DateTime.Now</param>
            public object Eval(string expression)
            {
                // 代码
                var text = string.Format(@"
                    using System;
                    public class Calculator
                    {{
                        public static object Evaluate() {{ return {0}; }}
                    }}", expression);
    
                // 编译生成程序集
                var tree = SyntaxFactory.ParseSyntaxTree(text);
                var compilation = CSharpCompilation.Create(
                    "calc.dll",
                    new[] { tree },
                    options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                    references: new[] { 
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
                    });
                Assembly compiledAssembly;
                using (var stream = new MemoryStream())
                {
                    var compileResult = compilation.Emit(stream);
                    compiledAssembly = Assembly.Load(stream.GetBuffer());
                }
    
                // 用反射执行方法
                var calculatorClass = compiledAssembly.GetType("Calculator");
                var evaluateMethod = calculatorClass.GetMethod("Evaluate");
                return evaluateMethod.Invoke(null, null);
            }
    }

    可以快乐的测试了

    var eval = new CsEvaluator();
    var b = eval.Eval("5 > 4");
    var d = eval.Eval("2.5");
    var dt1 = eval.Eval("new DateTime(2018,1,1)");
    var dt2 = eval.Eval("DateTime.Now");
  • 相关阅读:
    python之简单爬虫
    python之正则表达式
    python之面向对象
    python之模块与包
    python之循环嵌套与算法
    linux shell实现从函数返回数组
    linux脚本实现数组值相加
    linux中使用函数输出
    linux shelll中显示的意义
    lsof命令
  • 原文地址:https://www.cnblogs.com/surfsky/p/12918566.html
Copyright © 2020-2023  润新知