在运行时从代码文件执行c#代码

Vin*_*rya 45 .net c# runtime csharpcodeprovider

我有一个包含按钮的WPF C#应用程序.

按钮单击的代码写在单独的文本文件中,该文件将放在应用程序运行时目录中.

我想在单击按钮时执行放置在文本文件中的代码.

知道怎么做吗?

aco*_*aum 89

用于执行在fly类方法上编译的代码示例:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string source =
            @"
namespace Foo
{
    public class Bar
    {
        public void SayHello()
        {
            System.Console.WriteLine(""Hello World"");
        }
    }
}
            ";

             Dictionary<string, string> providerOptions = new Dictionary<string, string>
                {
                    {"CompilerVersion", "v3.5"}
                };
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

            CompilerParameters compilerParams = new CompilerParameters
                {GenerateInMemory = true,
                 GenerateExecutable = false};

            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);

            if (results.Errors.Count != 0)
                throw new Exception("Mission failed!");

            object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
            MethodInfo mi = o.GetType().GetMethod("SayHello");
            mi.Invoke(o, null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


jas*_*son 35

您可以使用它Microsoft.CSharp.CSharpCodeProvider来动态编译代码.特别是,请参阅CompileAssemblyFromFile.


Adi*_*ter 21

我建议看一下Microsoft Roslyn,特别是它的ScriptEngine类.以下是一些很好的例子:

  1. Roslyn Scripting API简介
  2. 使用Roslyn ScriptEngine为ValueConverter处理用户输入.

用法示例:

var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Run Code Online (Sandbox Code Playgroud)

  • 在搜索下载之前,只需使用Package-Manager:`Install-Package Roslyn` (3认同)