我想知道是否可以将C#代码片段保存到文本文件(或任何输入流),然后动态执行它们?假设提供给我的内容可以在任何Main()块中编译好,是否可以编译和/或执行此代码?出于性能原因,我更愿意编译它.
至少,我可以定义一个他们需要实现的接口,然后他们将提供一个实现该接口的代码"section".
Nol*_*rin 167
C#/所有静态.NET语言的最佳解决方案是使用CodeDOM进行此类操作.(作为一个注释,它的另一个主要目的是动态构造代码,甚至整个类.)
这是LukeH博客的一个很好的简短例子,它使用一些LINQ也只是为了好玩.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
Run Code Online (Sandbox Code Playgroud)
这里最重要的类是CSharpCodeProvider利用编译器动态编译代码.如果您想再运行代码,您只需要使用一些反射来动态加载程序集并执行它.
下面是C#中的另一个示例(虽然稍微简洁一点)另外向您展示了如何使用System.Reflection命名空间运行运行时编译的代码.
tug*_*erk 55
您可以将一段C#代码编译到内存中,并使用Roslyn 生成汇编字节.它已经提到但是值得为此添加一些Roslyn示例.以下是完整的示例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
namespace RoslynCompileSample
{
class Program
{
static void Main(string[] args)
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
using System;
namespace RoslynCompileSample
{
public class Writer
{
public void Write(string message)
{
Console.WriteLine(message);
}
}
}");
string assemblyName = Path.GetRandomFileName();
MetadataReference[] references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
};
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
}
else
{
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
Type type = assembly.GetType("RoslynCompileSample.Writer");
object obj = Activator.CreateInstance(type);
type.InvokeMember("Write",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
new object[] { "Hello World" });
}
}
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*ink 38
其他人已经就如何在运行时生成代码给出了很好的答案,所以我想我会解决你的第二段.我对此有一些经验,只想分享我从这次经历中吸取的教训.
至少,我可以定义一个他们需要实现的接口,然后他们将提供一个实现该接口的代码"section".
如果您使用interface基本类型,则可能会出现问题.如果您interface将来添加一个新方法,那么实现interface现在的所有现有客户端提供的类都将变为抽象,这意味着您将无法在运行时编译或实例化客户端提供的类.
在发布旧接口大约1年后以及在分发需要支持的大量"遗留"数据之后添加新方法时,我遇到了这个问题.我最终创建了一个继承旧接口的新接口,但这种方法使得加载和实例化客户端提供的类变得更加困难,因为我必须检查哪个接口可用.
我当时想到的一个解决方案是使用实际的类作为基类型,如下所示.类本身可以标记为抽象,但所有方法都应该是空虚拟方法(而不是抽象方法).然后,客户端可以覆盖他们想要的方法,并且可以向基类添加新方法,而不会使现有客户端提供的代码无效.
public abstract class BaseClass
{
public virtual void Foo1() { }
public virtual bool Foo2() { return false; }
...
}
Run Code Online (Sandbox Code Playgroud)
无论这个问题是否适用,您都应该考虑如何对代码库和客户端提供的代码之间的接口进行版本控制.
Chr*_*ini 11
发现这很有用 - 确保编译后的程序集引用您当前引用的所有内容,因为您很有可能希望正在编译的 C# 在发出此内容的代码中使用某些类等:
(字符串code是正在编译的动态 C#)
var refs = AppDomain.CurrentDomain.GetAssemblies();
var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
compileParams.GenerateInMemory = true;
compileParams.GenerateExecutable = false;
var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
var asm = compilerResult.CompiledAssembly;
Run Code Online (Sandbox Code Playgroud)
在我的例子中,我发出了一个类,它的名称存储在一个字符串中className,它有一个名为 的公共静态方法Get(),返回类型为StoryDataIds。这是调用该方法的样子:
var tempType = asm.GetType(className);
var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);
Run Code Online (Sandbox Code Playgroud)
警告:编译可能会令人惊讶,极其缓慢。一小段相对简单的 10 行代码块在我们相对较快的服务器上以正常优先级在 2-10 秒内编译。您永远不应该将调用CompileAssemblyFromSource()与具有正常性能预期的任何内容联系起来,例如 Web 请求。相反,在低优先级线程上主动编译您需要的代码,并有一种方法来处理需要准备好该代码的代码,直到它有机会完成编译。例如,您可以在批处理作业过程中使用它。
小智 5
我最近需要生成用于单元测试的进程。这篇文章很有用,因为我创建了一个简单的类来使用字符串代码或项目中的代码来执行此操作。要构建此类,您需要ICSharpCode.Decompiler和Microsoft.CodeAnalysisNuGet 包。这是课程:
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
public static class CSharpRunner
{
public static object Run(string snippet, IEnumerable<Assembly> references, string typeName, string methodName, params object[] args) =>
Invoke(Compile(Parse(snippet), references), typeName, methodName, args);
public static object Run(MethodInfo methodInfo, params object[] args)
{
var refs = methodInfo.DeclaringType.Assembly.GetReferencedAssemblies().Select(n => Assembly.Load(n));
return Invoke(Compile(Decompile(methodInfo), refs), methodInfo.DeclaringType.FullName, methodInfo.Name, args);
}
private static Assembly Compile(SyntaxTree syntaxTree, IEnumerable<Assembly> references = null)
{
if (references is null) references = new[] { typeof(object).Assembly, typeof(Enumerable).Assembly };
var mrefs = references.Select(a => MetadataReference.CreateFromFile(a.Location));
var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), new[] { syntaxTree }, mrefs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (result.Success)
{
ms.Seek(0, SeekOrigin.Begin);
return Assembly.Load(ms.ToArray());
}
else
{
throw new InvalidOperationException(string.Join("\n", result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")));
}
}
}
private static SyntaxTree Decompile(MethodInfo methodInfo)
{
var decompiler = new CSharpDecompiler(methodInfo.DeclaringType.Assembly.Location, new DecompilerSettings());
var typeInfo = decompiler.TypeSystem.MainModule.Compilation.FindType(methodInfo.DeclaringType).GetDefinition();
return Parse(decompiler.DecompileTypeAsString(typeInfo.FullTypeName));
}
private static object Invoke(Assembly assembly, string typeName, string methodName, object[] args)
{
var type = assembly.GetType(typeName);
var obj = Activator.CreateInstance(type);
return type.InvokeMember(methodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args);
}
private static SyntaxTree Parse(string snippet) => CSharpSyntaxTree.ParseText(snippet);
}
Run Code Online (Sandbox Code Playgroud)
要使用它,请调用Run以下方法:
void Demo1()
{
const string code = @"
public class Runner
{
public void Run() { System.IO.File.AppendAllText(@""C:\Temp\NUnitTest.txt"", System.DateTime.Now.ToString(""o"") + ""\n""); }
}";
CSharpRunner.Run(code, null, "Runner", "Run");
}
void Demo2()
{
CSharpRunner.Run(typeof(Runner).GetMethod("Run"));
}
public class Runner
{
public void Run() { System.IO.File.AppendAllText(@"C:\Temp\NUnitTest.txt", System.DateTime.Now.ToString("o") + "\n"); }
}
Run Code Online (Sandbox Code Playgroud)