如何查看一个类是否已经实现了与 Roslyn 的接口 [英] How to see if a class has implemented the interface with Roslyn

查看:29
本文介绍了如何查看一个类是否已经实现了与 Roslyn 的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是 Roslyn 的新手,所以希望这不是一个太愚蠢的问题.

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.

推荐答案

您可以使用 ITypeSymbol.FindImplementationForInterfaceMember 来达到此目的.

You can use ITypeSymbol.FindImplementationForInterfaceMember for this purpose.

基本上,您需要遍历接口的所有 IMethodSymbol 并检查所讨论的类型是否定义了与上述方法的返回值相等的方法.

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.

这是一个草稿:

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;

这篇关于如何查看一个类是否已经实现了与 Roslyn 的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆