问题描述
使用语句 Roslyn 脚本/代码排序和删除(未使用)?我正在寻找一些 .NET/Roslyn(编译器即服务)代码,它们可以在项目中运行并对未使用的 using 语句进行排序和删除.我相信罗斯林有可能吗?谁能指点我可以重写的代码?
Sort and remove (unused) using statements Roslyn script/code? I'm looking for some .NET/Roslyn (compiler as service) code that can run through a project and sort and remove unused using statements. I believe this is possible with Roslyn? Can anyone point me to code that could do this rewrite?
推荐答案
这是 Visual Studio 中的一个功能,但在学术上我认为你会从 SyntaxTree 中收集 using 语句,如下所示:
This is a feature in Visual Studio, but academically I think you would collect using statements from your SyntaxTree like this:
var usings = syntaxTree.Root.DescendentNodes().Where(node is UsingDirectiveSyntax);
...并将其与符号表解析的命名空间进行比较,如下所示:
...and compare that to the namespaces resolved by the symbol table like this:
private static IEnumerable<INamespaceSymbol> GetNamespaceSymbol(ISymbol symbol)
{
if (symbol != null && symbol.ContainingNamespace != null)
yield return symbol.ContainingNamespace;
}
var ns = semanticModel.SyntaxTree.Root.DescendentNodes().SelectMany(node =>
GetNamespaceSymbol(semanticModel.GetSemanticInfo(node).Symbol)).Distinct();
这篇关于使用语句 Roslyn 脚本/代码排序和删除(未使用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!