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

发布于 2024-10-02 01:01:23 字数 169 浏览 2 评论 0原文

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

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

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

知道如何做到这一点吗?

I have a WPF C# application that contains a button.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

浮云落日 2024-10-09 01:01:23

用于执行即时编译类方法的代码示例:

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

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);
        }
    }
}
巡山小妖精 2024-10-09 01:01:23

您可以使用 Microsoft. CSharp.CSharpCodeProvider 即时编译代码。特别是,请参阅 从文件编译程序集

You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.

枉心 2024-10-09 01:01:23

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

  1. Roslyn 脚本 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);

I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class.
Here are a few good examples to start with:

  1. Introduction to the Roslyn Scripting API
  2. Using Roslyn ScriptEngine for a ValueConverter to process user input.

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);
帝王念 2024-10-09 01:01:23

看起来有人为此创建了一个名为 C# Eval。

编辑:更新了指向 Archive.org 的链接,因为原始网站似乎已死。

Looks like someone created a library for this called C# Eval.

EDIT: Updated link to point to Archive.org as it seems like the original site is dead.

情徒 2024-10-09 01:01:23

您需要的是 CSharpCodeProvider 类

有几个示例可以帮助您了解它是如何工作的。

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

这个示例的要点是,实际上您可以立即完成所有操作。

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

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

这个例子很好,因为您可以创建 dll 文件,因此可以在其他应用程序之间共享。

基本上你可以搜索 http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 并获取更多有用的链接。

What you need is a CSharpCodeProvider Class

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

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

This example is good coz you can create dll file and so it can be shared between other applications.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文