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

3

Suppose I have a class like

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();
}
}

在编写以下代码之前,我如何确定 ImplementationClass 类实现了 ISampleInterface 接口?

SampleInterface obj = new ImplementationClass();
obj.SampleMethod();

有没有方法...请讨论。谢谢。

如果你需要知道这个,那么在执行时你肯定有某些东西 - 你有一个对象吗,还是只有类型的名称,或者其他什么? - Jon Skeet
看一下类的代码或元数据。 - Ben Robinson
1
@JonSkeet也许我错了,但我认为OP是在询问如何在设计时确定它。 - Ben Robinson
1
@BenRobinson:基本上不清楚... - Jon Skeet
我认为“在编写代码SampleInterface obj = new ImplementationClass();之前”意味着他没有对象实例,并希望对类型进行测试。 - Olivier Jacot-Descombes
5个回答

13

is关键字是这个问题的好解决方案。你可以测试一个对象是否为接口,或者是另一个类。你可以像这样做:

if (obj is ISampleInterface)
{
     //Yes, obj is compatible with ISampleInterface
}

如果你在运行时没有对象实例,但有一个Type,你可以使用IsAssignableFrom:

Type type = typeof(ISampleInterface);
var isassignable = type.IsAssignableFrom(otherType);

5

您可以使用反射:

bool result = typeof(ISampleInterface).IsAssignableFrom(typeof(ImplementationClass));

3
    public static bool IsImplementationOf(this Type checkMe, Type forMe)
    {
        foreach (Type iface in checkMe.GetInterfaces())
        {
            if (iface == forMe)
                return true;
        }

        return false;
    }

使用以下方式调用:

if (obj.GetType().IsImplementationOf(typeof(SampleInterface)))
    Console.WriteLine("obj implements SampleInterface");

1

当您硬编码实现类时,您知道它实现了哪些接口,因此您可以简单地查看源代码或文档以了解一个类实现了哪些接口。

如果您收到一个未知类型的对象,则有几种方法可以检查接口的实现:

void Test1(object a) {
    var x = a as IMyInterface;
    if (x != null) {
        // x implements IMyInterface, you can call SampleMethod
    }
}

void Test2(object a) {
    if (a is IMyInterface) {
        // a implements IMyInterface
        ((IMyInterface)a).SampleMethod();
    }
}

1

一个模式(由FxCop推荐)是

SampleInterface i = myObject as SampleInterface;
if (i != null) {
    // MyObject implements SampleInterface
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接