我有一个CSharpCompilation
包含SyntaxTree
s数组的实例,我正在尝试查找从类继承的所有类声明。
例如
// Not in syntax tree but referenced in project
public class Base{}
// In syntax tree, how to find all such classes?
public class MyClass : Base {}
我已经尝试了一些方法,但是对所有选项都有些困惑,似乎找不到正确的方法来做到这一点。
我试图获取符号,但这对继承的类型不起作用
SyntaxTree[] trees = context.CSharpCompilation.SyntaxTrees;
IEnumerable<ISymbol> symbols = context.CSharpCompilation.GetSymbolsWithName(x => x == typeof(Base).Name, SymbolFilter.Type);
罗斯林(Roslyn)颇为陌生,非常感谢您提供有关实现此目标的任何建议或指示。
所以我想出了以下内容,它将递归地检查所有类的继承类型
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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句