泛型集合型式试验 [英] Generic collections type test
问题描述
我想根据给定的集合类型(使用反射)进行某些操作,无论是通用型的。
I'd like to make some operations according to a given collection type (using reflexion), regardless of the generic type.
下面是我的代码:
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
}
}
它适用于现在,但它得到明显的,我认为这不是最安全的解决方案。
It works for now, but it gets obvious to me that it's not the most safe solution.
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
}
}
我试过太多,它actualy编译,但没有工作...
我也试图测试的所有接口给出集合类型,但它意味着在集合接口的排他性...
I tried that too, it actualy compiles but doesn't work... I also tried to test all interfaces of the given collection type, but it implies an exclusivity for interfaces in collections...
我希望我自己清楚,我的英语缺乏培训:)
I hope I made myself clear, my english lack of training :)
推荐答案
如果你想看看是否有实现特定泛型类型,那么你就需要做到这一点:
If you want to see if something implements a specific generic type, then you would need to do this:
if(a_type.IsGenericType && a_type.GetGenericTypeDefinition() == typeof(List<>))
的
GetGenericTypeDefinition()
方法将返回未绑定的泛型类型为你测试反对。
The GetGenericTypeDefinition()
method will return the unbounded generic type for you test against.
这篇关于泛型集合型式试验的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!