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


当前回答

对我有用的是:

断言。IsNotNull (typeof (YourClass) .GetInterfaces()。(i => i == typeof (ISomeInterface)));

其他回答

我使用

断言。(myObject是ImyInterface);

在我的单元测试中测试myObject是一个实现了我的接口ImyInterface的对象。

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

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

or

IBlah myTest = originalObject as IBlah

if (myTest != null)
    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

这篇文章是一个很好的答案。

public interface IMyInterface {}

public class MyType : IMyInterface {}

这是一个简单的例子:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType))

or

typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))