如何确定类型是否使用 C# 反射实现接口 [英] How to determine if a type implements an interface with C# reflection
本文介绍了如何确定类型是否使用 C# 反射实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C#
中的 reflection 是否提供了一种方法来确定某些给定的 System.Type
类型是否为某些接口建模?
Does reflection in C#
offer a way to determine if some given System.Type
type models some interface?
public interface IMyInterface {}
public class MyType : IMyInterface {}
// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
推荐答案
您有几个选择:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
对于通用接口,它有点不同.
For a generic interface, it’s a bit different.
typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))
这篇关于如何确定类型是否使用 C# 反射实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文