4
我想根据给定的集合类型(使用反射)进行一些操作,而不考虑泛型类型。通用集合类型测试
这里是我的代码:
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
}
}
我试过太多,它actualy编译,但没有工作... 我也试图测试给出集合类型的所有接口,但它在集合意味着排他性的接口...
我希望我自己清楚,我的英语缺乏培训:)
做'a_type.ToString()。'它说什么? – 2012-04-27 18:04:16
我怀疑你正试图解决错误的问题。向泛型代码添加特定于类型的检查是很臭的。 – n8wrl 2012-04-27 18:04:50
* a_type.ToString()=> System.Collections.Generic.List'1 [MyClass] – s0ubap 2012-04-27 18:08:57