我正在尝试实现一个 ICodeIssueProvider
来检测一个类(或其基类型之一)是否具有某个属性。
public IEnumerable<CodeIssue> GetIssues(IDocument document,
CommonSyntaxNode node,
CancellationToken cancellationToken)
{
var methodDeclaration = (MethodDeclarationSyntax)node;
var semanticModel = document.GetSemanticModel(cancellationToken);
var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration);
var typeSymbol = methodSymbol.ContainingType;
// The following only gets attributes declared on this class, how to
// also include those declared on a base class ?
var attributes = typeSymbol.GetAttributes();
有没有比沿着 typeSymbol.BaseType
一直走到 System.Object
并在途中调用 GetAttributes()
更好的方法?
此外,是否有比走上 .BaseType
并手动检查更好的方法来检查 typeSymbol
是否派生自特定类
(是的,从下面的示例中可以看出检查 MethodDeclarationSyntax
节点而不是 ClassDeclarationSyntax
节点的原因)
最佳答案
tldr; 不,没有单一方法调用来执行此操作(截至 2012 年 9 月 CTP Roslyn)。
您需要搜索的父类可能(并且通常是)与您所在的类完全独立的语法树。如果您的所有类都在一个 namespace
声明中(不寒而栗)那么您可以从那个 SyntaxNode
根搜索。
很有可能,您的类是每个文件一个,因此尽管它们共享相同的命名空间,但它们不在相同的语法树根目录下。
Roslyn 引起了很多麻烦,因为语法树更类似于代码文件的布局,而不是代码表示的类型。
可能有一种方法可以从该 namsepace
下存在的所有类中创建一个新的语法树(现有语法树是不可变的),然后搜索该树。对我来说,这感觉比需要的要复杂得多,尤其是因为 walking-up-parents 方法更易于维护。
关于c# - 查找基本类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700693/