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


当前回答

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

if (obj is IMyInterface myObj)

这和

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

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

其他回答

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

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
}

这应该可以工作:

MyInstace.GetType().GetInterfaces();

但也很好:

if (obj is IMyInterface)

甚至(不是很优雅):

if (obj.GetType() == typeof(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.
             }
        }

对我有用的是:

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