How to see if a class has implemented the interfac

2019-05-10 19:48发布

I'm still new at Roslyn, so hopefully this isn't too stupid of a question.

What I'm looking for is a way to see if a class has implemented all the methods of an interface and if not, the highlight the interface, just like the built in "Implement interface" does.

So far I can see if the method name is implemented, but I haven't found a way to see if the right returntype is set on the method.

1条回答
贪生不怕死
2楼-- · 2019-05-10 20:38

You can use ITypeSymbol.FindImplementationForInterfaceMember for this purpose.

Basically what you'd need is to go through all IMethodSymbols of the interface and check if the type in question defines a method which equals the returned value of the above method.

Here's a draft:

var interfaceType = ...
var typeInQuestion = ...
foreach(var interfaceMember in interfaceType.GetMembers().OfType<IMethodSymbol>())
{
  var memberFound = false;
  foreach(var typeMember in typeInQuestion .GetMembers().OfType<IMethodSymbol>())
  {
    if (typeMember.Equals(typeInQuestion.FindImplementationForInterfaceMember(interfaceMember)))
    {
      // this member is found
      memberFound = true;
      break;
    }
  }
  if (!memberFound)
  {
    return false;
  }
}
return true;
查看更多
登录 后发表回答