Search for type declaration method

Given a MethodDeclarationSyntax object, how can I find out a method declaring a type?

My actual problem is that I need to find out if the reference method of the interface method is used or not.

For example, given the code below, if I have a MethodDeclarationSyntax method for the Dispose () method, how can I conclude that this is an implementation of IDisposable.Dispose ()?

using System;
abstract class InterfaceImplementation : IDisposable
{
    public abstract void Dispose();
}

I tried to get a method declaring the type (and checking the type) without success (the Parent property returns me the InterfaceImplementation class).

I also tried to capture the semantic symbol for the method:

var methodSymbol = (MethodSymbol) semanticModel.GetDeclaredSymbol(methodDeclaration);

but could not find anything that could help me.

Ideas?

+5
source share
2 answers

, , . :

MethodSymbol method = ...;
TypeSymbol type = method.ContainingType;
MethodSymbol disposeMethod = (MethodSymbol)c.GetSpecialType(SpecialType.System_IDisposable).GetMembers("Dispose").Single();
bool isDisposeMethod = method.Equals(type.FindImplementationForInterfaceMember(disposeMethod));

, , , Dispose, , , IDisposable. # , . , ": IDisposable" InterfaceImplementation, IDisposable, Dispose() .

+7

(, MethodDeclarationSyntax) . , Dispose IDisposable. , , IDisposable . , , IDisposable, , . ( System.IDisposable? MyNamespace.IDisposable?)

​​, , .

, (EDIT: , , . ). .

, , MethodSymbol IDisposable.Dispose(), - :

SyntaxTree unit = SyntaxTree.ParseCompilationUnit(code);

MethodDeclarationSyntax method = …;

var compilation = Compilation.Create("test")
    .AddReferences(new AssemblyFileReference(typeof(object).Assembly.Location))
    .AddSyntaxTrees(unit);

SemanticModel model = compilation.GetSemanticModel(unit);

MethodSymbol methodSymbol = (MethodSymbol)model.GetDeclaredSymbol(method);

var typeSymbol = methodSymbol.ContainingType;

var idisposableDisposeSymbol = model.BindExpression(
    0, Syntax.ParseExpression("System.IDisposable.Dispose()")).Symbol;

var implementation = typeSymbol.FindImplementationForInterfaceMember(
    idisposableDisposeSymbol);

bool methodImplementsDispose = methodSymbol == implementation;
+4

All Articles