我有一个包含按钮的 WPF C# 应用程序。
按钮单击事件的代码被编写在一个独立的文本文件中,并将放置在应用程序运行目录中。
我想要在按钮点击时执行放置在文本文件中的代码。
有什么好的方法吗?
我有一个包含按钮的 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);
}
}
}
我推荐看一下Microsoft Roslyn,尤其是它的ScriptEngine
类。以下是几个很好的起点示例:
用法示例:
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);
Install-Package Roslyn
- Martin BraunmyCompilerParameters.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并获得更多有用的链接。