Reputation: 9426
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?
Upvotes: 3
Views: 294
Reputation: 3293
Use ITypeSymbol.FindImplementationForInterfaceMethod. These methods are not supposed to be findable "by name".
Upvotes: 2
Reputation: 9426
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)
Upvotes: 6