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


当前回答

对我有用的是:

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

其他回答

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

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

我有这样一种情况,我把一个变量传递给一个方法,不确定它是一个接口还是一个对象。

目标是:

如果item是一个接口,则基于该接口实例化一个对象,该接口是构造函数调用中的参数。 如果项目是一个对象,返回null,因为构造函数为我的调用期望一个接口,我不希望代码坦克。

我通过以下方法做到了这一点:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);
    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

对我有用的是:

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

如果你想在检查后使用类型转换对象: 从c# 7.0开始:

if (obj is IMyInterface myObj)

这和

IMyInterface myObj = obj as IMyInterface;
if (myObj != null)

参见.NET文档:模式匹配概述