为罗斯林提供某种方法的呼叫者信息



我有一种带有1个过载的方法,我想和罗斯林一起找出有人在调用过载方法并在这种情况下显示提示。

这些方法看起来像这样:

public void Info(string message, [CallerMemberName] string memberName = "")
{
}

public void Info(string message, string secondMessage, [CallerMemberName] string memberName = "")
{
}


例如,如果有人类型:

Info("The message", secondMessage: "Second message");

我想向开发人员展示一些信息。


可以使用Roslyn吗?

可以使用Roslyn做到这一点?

是。您需要从语义模型中获取方法符号,然后使用FindReferencesAsync

// Get your semantic model
var semanticModel = compilation.GetSemanticModel(tree);
//Or
var semanticModel = document.GetSemanticModelAsync();
// Get the method you want to find references to.
// You have a lot of ways to do that, but for example:
var method = doc.GetSyntaxRootAsync().
     Result.DescendantNodes().
     OfType<InvocationExpressionSyntax>().
     First();
//Or
var method = root.DescendantNodes().
     OfType<InvocationExpressionSyntax>().
     First();
//Then get the symbol info of the method
var methodSymbol = semanticModel.GetSymbolInfo(method).Symbol;
// And finally
SymbolFinder.FindReferencesAsync(methodSymbol, solution).Result

我建议阅读有关SolutionProjectDocumentSyntaxTreeRootNodeCompilationSemanticModel的信息。

一旦您理解这一点,就可以很容易地将分析器写成您想要的东西。我可以在这里粘贴一个分析仪示例,但是您可以在网络中找到更多(例如,在我的评论中检查链接)。

根据场景, May 仅添加[Obsolete]

[Obsolete("You're probably doing it wrong, neighbour", false)]
public void Info(string message, string secondMessage,
     [CallerMemberName] string memberName = "")

如果您想从自己的某些代码中调用它而没有警告:

#pragma warning disable 0618
Info("foo", "bar", "blap");
#pragma warning restore 0618

最新更新