问题描述
我有一个 CSharpCompilation
实例,其中包含一个 SyntaxTree
s数组,我正在尝试查找所有类声明从类继承的
I have a CSharpCompilation
instance containing an array of SyntaxTree
s and I am trying to find all the class declarations that inherit from a class
例如
// Not in syntax tree but referenced in project
public class Base{}
// In syntax tree, how to find all such classes?
public class MyClass : Base {}
我已经尝试了一些方法,但是有点混淆了所有选项,似乎找不到正确的方法。
I've tried a few things but am a bit confused with all the options and can't seem to find the right way to do this.
我尝试获取符号,但这不适用于继承的类型
I've tried to get the symbols but this doesn't work for inherited types
SyntaxTree[] trees = context.CSharpCompilation.SyntaxTrees;
IEnumerable<ISymbol> symbols = context.CSharpCompilation.GetSymbolsWithName(x => x == typeof(Base).Name, SymbolFilter.Type);
罗斯林(Roslyn)非常陌生,对于实现此目标的任何建议或指示,将不胜感激。 / p>
Quite new to Roslyn and would be most grateful for any suggestions or pointers for how to achieve this.
推荐答案
所以我想到了以下内容,它将递归检查所有类的继承类型
So I came up with the following which will recursively check all classes for the inherited type
public class BaseClassRewriter : CSharpSyntaxRewriter
{
private readonly SemanticModel _model;
public BaseClassRewriter(SemanticModel model)
{
_model = model;
}
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
var symbol = _model.GetDeclaredSymbol(node);
if (InheritsFrom<BaseClass>(symbol))
{
// hit!
}
}
private bool InheritsFrom<T>(INamedTypeSymbol symbol)
{
while (true)
{
if (symbol.ToString() == typeof(T).FullName)
{
return true;
}
if (symbol.BaseType != null)
{
symbol = symbol.BaseType;
continue;
}
break;
}
return false;
}
}
这篇关于查找所有类声明,而不是使用Roslyn继承其他类声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!