问题
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