简体   繁体   English

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

[英]execute c# code at runtime from code file

I have a WPF C# application that contains a button.我有一个包含按钮的WPF C#应用程序。

The code of the button click is written in separate text file which will be placed in the applications runtime directory.单击按钮的代码写在单独的文本文件中,该文件将放置在应用程序运行时目录中。

I want to execute that code placed in the text file on the click of the button.我想在单击按钮时执行放置在文本文件中的代码。

Any idea how to do this?知道如何做到这一点吗?

Code sample for executing compiled on fly class method:执行编译飞行类方法的代码示例:

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);
        }
    }
}

You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly.您可以使用Microsoft.CSharp.CSharpCodeProvider即时编译代码。 In particular, see CompileAssemblyFromFile .特别是,请参阅CompileAssemblyFromFile

I recommend having a look at Microsoft Roslyn , and specifically its ScriptEngine class.我建议看看Microsoft Roslyn ,特别是它的ScriptEngine类。 Here are a few good examples to start with:以下是一些很好的例子:

  1. Introduction to the Roslyn Scripting API Roslyn 脚本 API 简介
  2. Using Roslyn ScriptEngine for a ValueConverter to process user input . 使用 Roslyn ScriptEngine 作为 ValueConverter 来处理用户输入

Usage example:用法示例:

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);

Looks like someone created a library for this called C# Eval .看起来有人为此创建了一个名为C# Eval的库。

EDIT: Updated link to point to Archive.org as it seems like the original site is dead.编辑:更新了指向 Archive.org 的链接,因为原始站点似乎已死。

What you need is a CSharpCodeProvider Class你需要的是一个CSharpCodeProvider 类

There are several samples to understand how does it work.有几个示例可以了解它是如何工作的。

1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi 1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi

The important point of this example that you can do all things on flay in fact.这个例子的重点是你实际上可以做所有的事情。

myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;

2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime 2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime

This example is good coz you can create dll file and so it can be shared between other applications.这个例子很好,因为你可以创建 dll 文件,所以它可以在其他应用程序之间共享。

Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.基本上你可以搜索http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6并获得更多有用的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM