我正在尝试使用 Roslyn 编译器来动态生成程序集和类。
当我调用 Emit 时,我得到关于基本构造函数中的双引号值的错误,如下所示:
我应该如何对传递给的字符串中的双引号进行编码ParseText
?
var syntaxTree = CSharpSyntaxTree.ParseText(@"using System;
using System.Linq;
using Xxx.Operators;
namespace Xxx.Operators
{
public sealed class DuplicateOperator : Operator
{
public DuplicateOperator() : base(\""Sub\"")
{
}
public override long Execute(params Func<long>[] operands)
{
var firstValue = operands.First()() * 2;
return operands.Aggregate(firstValue, (a, b) => a - b());
}
}
}");
在以下代码中调用 Emit 时会生成错误,如果我将上面的引用值 (Sub) 替换为 String.Empty 之类的内容,则 Emit 成功。
var references = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic)
.Select(a => a.Location)
.Distinct()
.Select(l => MetadataReference.CreateFromFile(l))
.ToArray();
var compilation = CSharpCompilation.Create("Xxx.DynamicOperator", new []{syntaxTree}, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (result.Success)
{
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
}