如何确定一个类是否实现了特定的接口

Kei*_*sta 3 c# oop

假设我有类似的课程

interface ISampleInterface
{
  void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation: 
void ISampleInterface.SampleMethod()
{
    // Method implementation.
}

static void Main()
{
    // Declare an interface instance.
    ISampleInterface obj = new ImplementationClass();

    // Call the member.
    obj.SampleMethod();
}
}
Run Code Online (Sandbox Code Playgroud)

从main方法开始,如何在编写代码之前确定ImplementationClass该类是否已实现ISampleInterface,如下所示

SampleInterface obj = new ImplementationClass();
obj.SampleMethod();
Run Code Online (Sandbox Code Playgroud)

有什么办法....请讨论.谢谢.

vcs*_*nes 12

is关键字是一个很好的解决方案.您可以测试对象是接口,还是其他类.你会做这样的事情:

if (obj is ISampleInterface)
{
     //Yes, obj is compatible with ISampleInterface
}
Run Code Online (Sandbox Code Playgroud)

如果在运行时没有对象的实例,但是a Type,则可以使用IsAssignableFrom:

Type type = typeof(ISampleInterface);
var isassignable = type.IsAssignableFrom(otherType);
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 5

你可以使用反射:

bool result = typeof(ISampleInterface).IsAssignableFrom(typeof(ImplementationClass));
Run Code Online (Sandbox Code Playgroud)