如何从Roslyn中的using指令获取完全限定的名称空间? [英] How can I get the fully qualified namespace from a using directive in Roslyn?
问题描述
当您将鼠标悬停在VS2015中的简化的 using
指令"上时,它将显示标准名称.如何通过Roslyn插件获取此信息?它会使用 DiagnosticAnalyzer
吗? CodeFixProvider
?
When you hover over a "simplified" using
directive in VS2015, it shows you the fully-qualified name. How would I get this information via a Roslyn plugin? Would it be using a DiagnosticAnalyzer
? A CodeFixProvider
?
通读source.roslyn.codeplex.com,那里有大量信息,包括如何
Reading through source.roslyn.codeplex.com, there's tons of information there, including how to add a using
statement, and also how to simplify type names (including using
statements), but I'm unable to figure out how to go in reverse to get the fully-qualified name.
推荐答案
使用语义模型,您可以(显然)检索有关组成代码的语义的信息-这使您可以获得有关类型和其他构造的特定信息..
With the semantic model you can retrieve information about the semantics that make up your code (evidently) -- this allows you to get specific information about types and other constructs.
例如:
void Main()
{
var tree = CSharpSyntaxTree.ParseText(@"
using X = System.Text;
using Y = System;
using System.IO;
namespace ConsoleApplication1
{
}"
);
var mscorlib = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation", syntaxTrees: new[] { tree }, references: new[] { mscorlib });
var semanticModel = compilation.GetSemanticModel(tree);
var root = tree.GetRoot();
// Get usings
foreach (var usingDirective in root.DescendantNodes().OfType<UsingDirectiveSyntax>())
{
var symbol = semanticModel.GetSymbolInfo(usingDirective.Name).Symbol;
var name = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
name.Dump();
}
}
输出:
global :: System.Text
全局::系统
全局:: System.IO
global::System.Text
global::System
global::System.IO
如果您改用 SymbolDisplayFormat.CSharpErrorMessageFormat
,则会收到
System.Text
系统
System.IO
System.Text
System
System.IO
您可以选择自己感兴趣的内容,但是可以看到,无论有没有别名,它都可以正常工作.
Your choice what you're interested in but as you can see it works just fine with aliases and without.
这篇关于如何从Roslyn中的using指令获取完全限定的名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!