c# 动态编译

http://zhidao.baidu.com/question/130350599.html

我想在c#中通过动态编译实现一个科学计算器器功能,用户直接输入运算表达式即可,如256*56(145+56*254/345).然后通过动态编译返回结果。请给出代码或例子!~

问题补充:

比如说:将textbox1的用户输入语句如256*56(145+56*254/345)利用动态编译求出值后,在textbox2中将结果显示。我在编写一个矩阵工具,比如用户先导入需要计算的矩阵A,P,L,然后用户可以直接输入 类似(AT*PA)'AT*P*L;然后通过动态编译返回最终矩阵。
 最佳答案
要用到C#的编译器、反射功能,自己瞧着去吧
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

public class Example
{
    static void Main()
    {
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameter = new CompilerParameters();
        parameter.ReferencedAssemblies.Add("System.dll");
        parameter.GenerateExecutable = false;
        parameter.GenerateInMemory = true;

        CompilerResults result = provider.CompileAssemblyFromSource(parameter, 
            CreateCode("256*56*(145+56.0*254/345)"));//将你的式子放在这里
        if (result.Errors.Count > 0)
        {
            Console.WriteLine("动态编译出错了!");
        }
        else
        {
            Assembly assembly = result.CompiledAssembly;
            Type AType = assembly.GetType("ANameSpace.AClass");
            MethodInfo method = AType.GetMethod("AFunc");
            Console.WriteLine(method.Invoke(null, null));
        }
        Console.Read();
    }
    static string CreateCode( string para)
    { 
        return "using System; namespace ANameSpace{static class AClass{public static object AFunc(){return "+para+";}}}";
    }
}
原文地址:https://www.cnblogs.com/carl2380/p/2006363.html