Find classes which derive from a specific base class with Roslyn

僤鯓⒐⒋嵵緔 提交于 2019-12-12 00:08:22

问题


On this page following code is suggested to find classes which derive from a given type, but this code does not work because following line

var symbol = _model.GetDeclaredSymbol(node);

returns ISymbol, rather than expected INamedTypeSymbol.

On the answers to FAQs on this page , for getting the type of a variable declaration, following piece of code is suggested. However, this also throws an exception in run-time, saying that cast to ILocalSymbol is not valid.

var type = ((ILocalSymbol)model.GetDeclaredSymbol(variableDeclarator)).Type;

I tried looking into Roslyn source code to figure out a way and tried them but so far no success.

What I would like to do is, detect all classes in a solution which derive from DbContext class of EntityFramework. Can anybody suggest me a way to find this? Thanks in advance!


回答1:


Figured what was going wrong. Maybe will help somebody else not to lose much time.

ModelExtensions class in Microsoft.CodeAnalysis namespace has a method declaration with the name GetDeclaredSymbol. The method that needed to be called was the one in class CSharpExtensions in namespace Microsoft.CodeAnalysis.CSharp. If you already have a using statement to Microsoft.CodeAnalysis in the class, GetDeclaredSymbol method on ModelExtensions is called, which was the case for me. Took me time to figure out.

This method in CSharpExtensions class is the one that should be invoked:

public static INamedTypeSymbol GetDeclaredSymbol(
  this SemanticModel semanticModel, 
  BaseTypeDeclarationSyntax declarationSyntax, 
  CancellationToken cancellationToken = default(CancellationToken));


来源:https://stackoverflow.com/questions/31505199/find-classes-which-derive-from-a-specific-base-class-with-roslyn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!