IsAssignableFrom和GetInterface有什么区别?

Nes*_*cio 17 .net c# reflection

在.Net中使用反射,有什么区别:

   if (foo.IsAssignableFrom(typeof(IBar)))
Run Code Online (Sandbox Code Playgroud)

   if (foo.GetInterface(typeof(IBar).FullName) != null)
Run Code Online (Sandbox Code Playgroud)

哪个更合适,为什么?

什么时候一个或另一个失败?

Mar*_*ade 13

如果你只想查看某个类型是否实现了一个给定的接口,那么就好了,尽管GetInterface()可能更快,因为IsAssignableFrom()比GetInterface()做更多的内部检查.检查Type.GetInterfaces()的结果可能会更快,它返回两个其他方法仍然使用的相同内部列表.