gpt4 book ai didi

.net - 如何使用 Roslyn 添加对在内存流中编译的类型的引用?

转载 作者:行者123 更新时间:2023-12-04 15:22:08 25 4
gpt4 key购买 nike

作为编译的输入,我有一个包含以下代码的字符串:

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string EmailAddress { get; set; }
}

我有以下代码,请注意 [01] 处的注释.这里的目的是获取一个包含类的字符串(来自 this.Source 并将程序集的代码发送到 MemoryStream 中。
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
var assemblyName = Guid.NewGuid().ToString();
var syntaxTrees = CSharpSyntaxTree.ParseText(this.Source);

// build references up
var references = new List<MetadataReference>();
//[01] references.Add("System.dll"));

// set up compilation
var compilation = CSharpCompilation.Create(assemblyName)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(references)
.AddSyntaxTrees(syntaxTrees);

// build the assembly
Assembly assembly;
using (var stream = new MemoryStream())
{
// this is broked...
EmitResult compileResult = compilation.Emit(stream);
// [02] we get here, with diagnostic errors (check compileResult.Diagnostics)
assembly = Assembly.Load(stream.GetBuffer());
}

[02]我收到了 BadImageFormat异常,在 compileResult.Diagnostics 中有以下内容:
[0]: warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
[1]: (2,18): error CS0518: Predefined type 'System.Object' is not defined or imported
[2]: (4,16): error CS0518: Predefined type 'System.String' is not defined or imported
[3]: (4,40): error CS0518: Predefined type 'System.Void' is not defined or imported
[4]: (5,16): error CS0518: Predefined type 'System.String' is not defined or imported
[5]: (5,39): error CS0518: Predefined type 'System.Void' is not defined or imported
[6]: (6,16): error CS0518: Predefined type 'System.Int32' is not defined or imported
[7]: (6,31): error CS0518: Predefined type 'System.Void' is not defined or imported
[8]: (7,16): error CS0518: Predefined type 'System.String' is not defined or imported
[9]: (7,43): error CS0518: Predefined type 'System.Void' is not defined or imported
[10]: (2,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments

如果我添加一个 using System;在代码的开头,我收到以下错误:
error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)

这让我相信我无法从我坐的地方访问 System,这就是为什么我在该伪代码中 stub references.Add("System.dll")); .这显然是不正确的,但这是我的意图。

有关更多信息,此处的目的是然后动态创建生成类型的实例并将值分配给属性。

使编译器可以使用引用的正确方法是什么?

或者,是否有另一种方法来编译这样的类(从字符串输入)?

最佳答案

调用 AssemblyMetadata.CreateFromFile(path) method ,并通过 typeof(object).Assembly.Location (或其他程序集)。

关于.net - 如何使用 Roslyn 添加对在内存流中编译的类型的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26822811/

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