简体   繁体   中英

Get assembly name of referenced method

Using the SemanticModel in Roslyn is there a way to get the assembly name of the referenced method?

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);

Yes, there is. I guess these two lines should work in your code:

var containingAssembly = enclosingSymbol.ContainingAssembly;
var containingAssemblyName = containingAssembly.Name;

ContainingAssembly has the assembly name, location, etc. information. You may put a break point and inspect it.

If it does not work, below is the code I use for the same purpose, which is working fine:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM