在c#中测试对象是否实现给定接口的最简单方法是什么?(回答这个问题 在Java中)


当前回答

最近我试着用安德鲁·凯南的答案,但出于某种原因,它对我不起作用。我使用了这个方法,并且它有效(注意:可能需要写入名称空间)。

if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)

其他回答

@AndrewKennan的答案的一个变体,我最近在运行时获得的类型中使用了:

if (serviceType.IsInstanceOfType(service))
{
    // 'service' does implement the 'serviceType' type
}
if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

如果您在编译时就知道接口类型,并且拥有正在测试的类型的实例,那么使用is或作为操作符是正确的方法。其他人似乎没有提到的是类型。IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

我认为这比查看GetInterfaces返回的数组要简洁得多,而且也具有适用于类的优点。

    interface IItem
    {

    }

    class ItemImp : IItem
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            Type t = typeof(ItemImp);

            Console.WriteLine("t == typeof(IItem) -> {0}", t == typeof(IItem));
            Console.WriteLine("typeof(IItem).IsAssignableFrom(t) -> {0}", typeof(IItem).IsAssignableFrom(t));
            Console.WriteLine("t is IItem -> {0}", t is IItem);
            Console.WriteLine("new ItemImp() is IItem -> {0}", new ItemImp() is IItem);
        }
    }

// Here are outputs:
// t == typeof(IItem) -> False
// typeof(IItem).IsAssignableFrom(t) -> True
// t is IItem -> False
// new ItemImp() is IItem -> True

这应该可以工作:

MyInstace.GetType().GetInterfaces();

但也很好:

if (obj is IMyInterface)

甚至(不是很优雅):

if (obj.GetType() == typeof(IMyInterface))