使用 Roslyn 查找从特定基类派生的类 [英] Find classes which derive from a specific base class with Roslyn

查看:50
本文介绍了使用 Roslyn 查找从特定基类派生的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个页面下面的代码建议查找从给定类型派生的类,但此代码不起作用,因为以下行

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);

返回 ISymbol,而不是预期的 INamedTypeSymbol.

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;

我尝试查看 Roslyn 源代码以找出一种方法并尝试了它们,但到目前为止没有成功.

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

我想做的是,检测从 EntityFramework 的 DbContext 类派生的解决方案中的所有类.有人可以建议我找到这个的方法吗?提前致谢!

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!

推荐答案

弄清楚出了什么问题.也许会帮助别人不浪费太多时间.

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

Microsoft.CodeAnalysis 命名空间中的 ModelExtensions 类具有名为 GetDeclaredSymbol 的方法声明.需要调用的方法是命名空间 Microsoft.CodeAnalysis.CSharp 中的 CSharpExtensions 类中的方法.如果您已经在类中对 Microsoft.CodeAnalysis 有 using 语句,则调用 ModelExtensions 上的 GetDeclaredSymbol 方法,这就是我的情况.我花了一些时间来弄清楚.

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.

CSharpExtensions 类中的这个方法是应该被调用的方法:

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));

这篇关于使用 Roslyn 查找从特定基类派生的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆