2
我的问题是关于CSharpCompilerOptions
和using
语句传递给CSharpCompilation
的实例。Roslyn:CSharpCompilerOptions WithUsings的影响
我有一些文本解析的语法树:
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace RoslynCodeAnalysis
{
using System;
using System.Net; // Commenting this out causes errors
public class Writer
{
public void Write(string message)
{
WebClient client = new WebClient();
Console.WriteLine(message);
}
}
}");
的CSharpCompilation实例被创建如下。我没有提供简单的参考,但它确实添加了对System.Net和其他常见程序集的引用。
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
usings: new List<string> { "System", "System.Net" }));
的问题是,如果我注释掉使用System.Net,我得到的错误说:
CS0246:类型或命名空间名称“Web客户端”找不到(是 您是否缺少使用指令或装配参考?)
这是什么原因造成的?传递给CSharpCompilation的选项具有设置为System和System.Net的usings属性。这是正常行为还是我错过了什么?即使指定了using属性,源文本仍然需要使用using语句?我很确定我错过了一些东西!
我在这里猜测,但它似乎是全球命名空间...注意'///全局命名空间usings.'在http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/ CSharpCompilationOptions.cs,ffc9d5ff7f13d4a1第27行。如果我是对的,可以在'global ::'命名空间别名https://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx下访问这些命名空间,将其切换到'global :: WebClient client = new global :: WebClient();'它可以使用System.Net;'注释掉。 – Will
你好Will,谢谢你的建议,我试过了,仍然是同样的错误。我注意到源代码中的评论,并且我假设它对于所有语法树来说是“全局”的,就目前的编译单元而言。 – k25
@ will:No;那是不正确的。 – SLaks