简体   繁体   中英

Cannot retrieve explicit interface implemented member

I'm using Roslyn to analyze C# code and I've run into an issue when playing around with explicitly implemented interfaces. Given a type that implements an interface, I'm unable to retrieve explicitly implemented members by name. For example:

var tree = CSharpSyntaxTree.ParseText(@"
using System;

namespace ConsoleApplication1
{
    class MyClass : IDisposable
    {
        void IDisposable.Dispose()
        {
        }
        public void Dispose()
        {
        }
    }
}");

var Mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); 
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);

var myType = compilation.GetTypeByMetadataName("ConsoleApplication1.MyClass");
var dispose = myType.GetMembers("Dispose").SingleOrDefault();
//explicitDispose is null.
var explicitDispose = myType.GetMembers("IDisposable.Dispose").SingleOrDefault();

This only seems to be the case when the type lives within a namespace, the following code works fine.

var tree = CSharpSyntaxTree.ParseText(@"
class MyClass : IDisposable
{
    void IDisposable.Dispose()
    {
    }
    public void Dispose()
    {
    }
}");
var Mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); 
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);

var myType = compilation.GetTypeByMetadataName("MyClass");
var dispose = myType.GetMembers("Dispose").SingleOrDefault();
//explicitDispose is not null.
var explicitDispose = myType.GetMembers("IDisposable.Dispose").SingleOrDefault();

Does anyone know why this is occurring? Is there a better way to work with explicitly implemented interfaces?

It appears you need to provide the fully qualified method signature when it has been explicitly implemented:

var explicitDispose = myType.GetMembers("System.IDisposable.Dispose").SingleOrDefault();

(I was going to delete this question, but I see someone has marked it as a favorite, so I'll provide the answer that worked for me)

Use ITypeSymbol.FindImplementationForInterfaceMethod . These methods are not supposed to be findable "by name".

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