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


当前回答

这应该可以工作:

MyInstace.GetType().GetInterfaces();

但也很好:

if (obj is IMyInterface)

甚至(不是很优雅):

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

其他回答

对我有用的是:

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

这应该可以工作:

MyInstace.GetType().GetInterfaces();

但也很好:

if (obj is IMyInterface)

甚至(不是很优雅):

if (obj.GetType() == typeof(IMyInterface))
if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

例如:

if (obj is IMyInterface) {}

本课程:

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

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

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

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