gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:53:27 25 4
gpt4 key购买 nike

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

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

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

知道怎么做吗?

最佳答案

执行编译类方法的代码示例:

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

关于c# - 在运行时从代码文件执行 c# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4181668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com