在Roslyn中使用SemanticModel是否可以获取引用方法的程序集名称?
var refMethod = string.Empty;
var refClass = string.Empty;
var refDocument = string.Empty;
if (location.Document.TryGetSemanticModel(out var referenceSemanticModel))
{
var enclosingSymbol = referenceSemanticModel.GetEnclosingSymbol(location.Location.SourceSpan.Start);
if (!(enclosingSymbol is null))
{
refMethod = enclosingSymbol.Name;
refClass = enclosingSymbol.ContainingType.Name;
refDocument = Path.GetFileName(location.Location.SourceTree.FilePath);
答案 0 :(得分:2)
是的,有。我猜这两行应该在您的代码中起作用:
var containingAssembly = enclosingSymbol.ContainingAssembly;
var containingAssemblyName = containingAssembly.Name;
ContainingAssembly具有程序集名称,位置等信息。您可以放置一个断点并检查它。
如果它不起作用,下面是我出于相同目的使用的代码,效果很好:
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var invocationExpr = (InvocationExpressionSyntax)context.Node;
var memberAccessExpr = invocationExpr.Expression as MemberAccessExpressionSyntax;
var memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol as IMethodSymbol;
var namespace= memberSymbol?.ContainingNamespace;
var assemblyName = memberSymbol?.ContainingAssembly;
}