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


当前回答

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

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

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

其他回答

除了使用"is"操作符进行测试外,你还可以装饰你的方法,以确保传递给它的变量实现了特定的接口,如下所示:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

我不确定这是在哪个版本的。net中实现的,所以它可能在你的版本中不起作用。

这应该可以工作:

MyInstace.GetType().GetInterfaces();

但也很好:

if (obj is IMyInterface)

甚至(不是很优雅):

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

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

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

我使用

断言。(myObject是ImyInterface);

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

我通过使用is关键字实现了这一点。

但是我也需要一个新的对象来使用接口属性。 要实现这一点,您需要在Interface之后添加新变量。

objectToCheck is Interface newVariableWithInterfaceProperties

.

 public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
            RequestHandlerDelegate<TResponse> next)
        {
            if (request is ICacheableQuery cachableRequest)
            {
             // here cachableRequest now has the interface properties.
             }
        }