我希望扫描一组.cs文件,看看哪些文件调用了Nullable<T>的Value属性(查找所有引用)。例如,这将匹配:
class Program
{
static void Main()
{
int? nullable = 123;
int value = nullable.Value;
}
}我发现了Roslyn,并查看了一些示例,但其中许多都过时了,API非常庞大。我该怎么做呢?
在解析语法树之后,我被卡住了。这就是我到目前为止所知道的:
public static void Analyze(string sourceCode)
{
var tree = CSharpSyntaxTree.ParseText(sourceCode);
tree./* ??? What goes here? */
}发布于 2015-08-07 04:00:15
您可能正在寻找SymbolFinder类,特别是FindAllReferences方法。
听起来你在熟悉Roslyn方面有些困难。我有一系列的博客帖子来帮助人们认识罗斯林,叫做Learn Roslyn Now。
正如@SLaks提到的,您将需要访问我在Part 7: Introduction to the Semantic Model中介绍的语义模型
下面是一个示例,向您展示如何使用该API。如果可以,我会使用MSBuildWorkspace并从磁盘加载项目,而不是像这样在AdHocWorkspace中创建项目。
var mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var ws = new AdhocWorkspace();
//Create new solution
var solId = SolutionId.CreateNewId();
var solutionInfo = SolutionInfo.Create(solId, VersionStamp.Create());
//Create new project
var project = ws.AddProject("Sample", "C#");
project = project.AddMetadataReference(mscorlib);
//Add project to workspace
ws.TryApplyChanges(project.Solution);
string text = @"
class C
{
void M()
{
M();
M();
}
}";
var sourceText = SourceText.From(text);
//Create new document
var doc = ws.AddDocument(project.Id, "NewDoc", sourceText);
//Get the semantic model
var model = doc.GetSemanticModelAsync().Result;
//Get the syntax node for the first invocation to M()
var methodInvocation = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<InvocationExpressionSyntax>().First();
var methodSymbol = model.GetSymbolInfo(methodInvocation).Symbol;
//Finds all references to M()
var referencesToM = SymbolFinder.FindReferencesAsync(methodSymbol, doc.Project.Solution).Result;https://stackoverflow.com/questions/31861762
复制相似问题