检查类型是否实现通用接口而不考虑generics类型参数
我有一个界面
public interface MyInterface { }
实现是无关紧要的。 现在我想检查给定类型是否是该接口的实现。 这种方法失败了
public class MyClass : MyInterface { }
但我不知道怎么做检查。
public void CheckIfTypeImplementsInterface(Type type) { var result1 = typeof(MyInterface).IsAssignableFrom(type); --> false var result2 = typeof(MyInterface).IsAssignableFrom(type); --> true }
我需要做些什么才能使result1成为现实?
据我所知,唯一的方法是获取所有接口,看看通用定义是否与所需的接口类型匹配。
bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()) .Contains(typeof(MyInterface<,>));
编辑:正如乔恩在评论中指出的那样,你也可以这样做:
bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == typeof(MyInterface<,>));
通常,仅在接口包含一些不依赖于generics类型参数的function的情况下才需要这种行为。 如果您可以控制接口,那么最佳解决方案是使类型相关的部分inheritance自非类型相关部分。 例如,如果现有的集合接口不存在,可以将它们定义为:
interface ICountable { CollectionAttribute Attributes {get;} int Count {get;} } interface ICollection : IEnumerable ICountable { ... and other stuff ... }
如果使用ICollection
完成了这样的事情,那么期待IEnumerable
但是得到一个CatList
类型的对象的CatList
只是实现IList
将使用该对象的Count
成员没有问题(请注意List
实现非genericsICollection
,但其他IList
实现可能不会)。
事实上,如果您遇到使用代码以某种方式找到ICollection
的Count
方法的任务,当您期望IEnumerable
,可能值得构建像Dictionary
这样的东西Dictionary
这样一旦你发现CatList
实现了ICollection
你就可以构造一个方法的委托,该方法将其参数转换为ICollection
,在其上调用Count
,并返回结果。 如果你有这样的字典,那么如果给你另一个CatList
你将能够简单地从字典中调用委托。