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


当前回答

我使用

断言。(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.
             }
        }

例如:

if (obj is IMyInterface) {}

本课程:

检查typeof(MyClass). getinterfaces()是否包含该接口。

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

public interface IMyInterface {}

public class MyType : IMyInterface {}

这是一个简单的例子:

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

or

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

@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);