Using Roslyn, how to check if class comes from a local project, not the BCL or Nuget (etc)?

☆樱花仙子☆ 提交于 2019-12-08 07:02:37

问题


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.

How do I tell where a class comes from in Roslyn?


回答1:


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


来源:https://stackoverflow.com/questions/39200779/using-roslyn-how-to-check-if-class-comes-from-a-local-project-not-the-bcl-or-n

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