- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在使用 CSharpCompilation
类来编译 SyntaxTree
,其中根是一个类声明。我向构造函数传递了一个包含我的 using 语句的 CSharpCompilationOptions
对象。
我的理解是语法树将使用我通过的任何 using 语句的上下文进行编译。但是,当尝试访问在我传递给选项对象的“使用”之一中定义的类时,我收到一条错误消息,指出它在当前上下文中不存在。
我显然做错了什么。有人知道传递给 CSharpCompilationOptions
类时使用列表的用途吗?
这是代码:
public static void TestMethod()
{
string source = @"public class Test
{
public static void TestMethod()
{
string str = Directory.GetCurrentDirectory();
}
}";
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
List<string> usings = new List<string>()
{
"System.IO", "System"
};
List<MetadataFileReference> references = new List<MetadataFileReference>()
{
new MetadataFileReference(typeof(object).Assembly.Location),
};
//adding the usings this way also produces the same error
CompilationUnitSyntax root = (CompilationUnitSyntax)syntaxTree.GetRoot();
root = root.AddUsings(usings.Select(u => SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(u))).ToArray());
syntaxTree = CSharpSyntaxTree.Create(root);
CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings);
CSharpCompilation compilation = CSharpCompilation.Create("output", new[] { syntaxTree }, references, options);
using (MemoryStream stream = new MemoryStream())
{
EmitResult result = compilation.Emit(stream);
if (result.Success)
{
}
}
}
最佳答案
因此,事实证明 CSharpCompilationOptions.Usings
仅在编译脚本文件时在编译器中进行过检查。如果您跟踪引用资料,它最终会被使用 here , 在 if (inScript)
检查中。
我们可能需要更好地记录这一点。
关于c# - Roslyn - CSharpCompilation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24658381/
我想将一个已经存在的 CSharpCompilation 对象包含到一个新的 CSharpCompilation 对象中。类似于 c# 中的项目到项目引用。我目前的解决方案是在新编译中包含第一次编译的
我正在尝试使用 CSharpCompilation 编译程序集其中有一个简单的类,然后我可以在另一个也通过 CSharpCompilation 编译的程序中引用它.我有这个代码: 命名空间编译测试 {
我一直在尝试向服务器应用程序添加命令系统 问题是:不在项目内但 的命令.cs文件它们是在运行时从另一个文件夹编译的,不能包含任何东西。 编译器代码: static CompilerResults Co
我正在使用 CSharpCompilation 类来编译 SyntaxTree,其中根是一个类声明。我向构造函数传递了一个包含我的 using 语句的 CSharpCompilationOptions
首先,我使用 Windows 10 和 visual studio 2019,使用 .net core 3.1我正在使用来自 Nuget Microsoft.Net.Compilers 3.4.0 和
Roslyn 编译器和动力学 --> 我正在尝试编译仅在运行时已知的属性。 在 Visual Studio 中编译时代码有效。使用 Roslyn 编译时,动态属性为“未知”。 在这个示例单元测试中,我
有谁知道在使用 CSharpCompilation 的扩展方法 Emit 发出程序集时是否可以指定框架版本? 我们显然需要以 4.5.1 为目标,否则我们会遇到严重的运行时错误: MissingMet
如何转换: System.Linq.Expression.Expression 进入: Microsoft.CodeAnalysis.CSharp.CSharpCompilation 或进入: Mic
我正在尝试将一些 .net 代码移植到新的 Core 运行时,但我在移植一些即时编译时遇到了麻烦。 继续,它总是要求我提供对 System.Runtime 和 mscorlib 的引用,但不知道如何引
我正在开发一项服务,给定 Swagger 定义的 URL,使用 NSwag 为该服务生成 C# 代理。整个代理包含在一个 C# 文件中。 我想使用 Roslyn 将生成的代码自动编译为 .NET St
我想创建运行时类,但是当使用 Stimulsoft.Report.Dictionary 中的属性 [StiAlias("id")] 时; 发送错误: [0] = (1,101): 错误 CS0012:
我是一名优秀的程序员,十分优秀!