testing对象是否实现接口
如果一个对象在C#中实现给定的接口,最简单的方法是什么? ( 在Java中回答这个问题)
if (object is IBlah) 要么
 IBlah myTest = originalObject as IBlah if (myTest != null) 
 如果在编译时知道接口types,并且有一个正在testing的types的实例,那么使用is或as操作符是正确的方法。 其他人似乎没有提到的是Type.IsAssignableFrom : 
 if( typeof(IMyInterface).IsAssignableFrom(someOtherType) ) { } 
 我认为这比查看GetInterfaces返回的数组要好得多,而且还有类的工作优势。 
例如:
 if (obj is IMyInterface) {} 
对于class级:
 检查typeof(MyClass).GetInterfaces()包含接口。 
@ AndrewKennan的答案的一个变种我最终使用了在运行时获得的types:
 if (serviceType.IsInstanceOfType(service)) { // 'service' does implement the 'serviceType' type } 
除了使用“is”运算符进行testing之外,还可以修饰方法以确保传递给它的variables实现特定的接口,如下所示:
 public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable { //Some bubbly sorting } 
我不确定哪个版本的.Net这是实施,所以它可能无法在您的版本。
对我有效的是:
 Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface))); 
最近我尝试使用安德鲁凯南的答案,由于某种原因,我没有为我工作。 我用这个而不是它的工作(注:写入命名空间可能是必需的)。
 if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null) 
我用了
 Assert.IsTrue(myObject is ImyInterface); 
在我的unit testing中testingmyObject是一个实现了我的接口ImyInterface的对象的testing。
这篇文章是一个很好的答案。
 public interface IMyInterface {} public class MyType : IMyInterface {} 
这是一个简单的例子:
 typeof(IMyInterface).IsAssignableFrom(typeof(MyType)) 
要么
 typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface)) 
这应该工作:
 MyInstace.GetType().GetInterfaces(); 
但也很好:
 if (obj is IMyInterface) 
甚至(不是很优雅):
 if (obj.GetType() == typeof(IMyInterface))