使用 Roslyn,如何检查类是否来自本地项目,而不是 BCL 或 Nuget(等)? [英] Using Roslyn, how to check if class comes from a local project, not the BCL or Nuget (etc)?

查看:32
本文介绍了使用 Roslyn,如何检查类是否来自本地项目,而不是 BCL 或 Nuget(等)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个 Roslyn 代码分析器;如果 ObjectCreationExpression 正在从本地类(在当前项目中或当前解决方案中的项目中)创建对象,则需要确定;或者如果该类来自其他地方,例如基类库或 Nuget 包等.

I want to write a Roslyn code analyser; which needs to work out if an ObjectCreationExpression is creating an object from a local class (either in the current project or a project in the current solution); or if the class comes from somewhere else, like the Base Class Library or a Nuget package etc.

我如何知道 Roslyn 中某个类的来源?

推荐答案

你只能在语义模型的帮助下得到它.您可以获得构造函数的符号,并通过 检查类型来自哪里Locations 或 DeclaringSyntaxReferences,例如:

You can only get that with the help of the semantic model. You can get the symbol for the constructor, and the check where the type comes from via Locations or DeclaringSyntaxReferences, e.g.:

// ObjectCreationExpression node == ...;
// SemanticModel model = ...;
var symbol = model.GetSymbolInfo(node).Symbol; // the constructor symbol
var type = symbol.ContainingType; // the class symbol
var isFromSource = type.DeclaringSyntaxReferences.Length > 0

这篇关于使用 Roslyn,如何检查类是否来自本地项目,而不是 BCL 或 Nuget(等)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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