通用集合类型测试

我想根据给定的集合类型(使用reflection)进行一些操作,而不管generics类型。

这是我的代码:

void MyFct(Type a_type) { // Check if it's type of List if (a_type.Name == "List`1") { // Do stuff } // Check if it's type of Dictionary else if (a_type.Name == "Dictionary`2") { // Do stuff } } 

它现在有效,但对我来说很明显,它不是最安全的解决方案。

  void MyFct(Type a_type) { // Check if it's type of List if (a_type == typeof(List)) { // Do stuff } // Check if it's type of Dictionary else if (a_type == typeof(Dictionary)) { // Do stuff } } 

我也尝试过,它实际编译但不起作用……我也尝试测试给定集合类型的所有接口,但它暗示了集合中接口的排他性……

我希望我清楚自己,我的英语缺乏训练:)

如果您想查看某些东西是否实现了特定的generics类型,那么您需要这样做:

 if(a_type.IsGenericType && a_type.GetGenericTypeDefinition() == typeof(List<>)) 

GetGenericTypeDefinition()方法将返回针对您进行测试的无界generics类型。