由网友(积极废人)分享简介:我想,以确定是否一个通用对象类型(T)的方法类型参数是集合类型。我通常通过发送T作为一个Generic.List,但它可以是任何集合类型,因为这是用在辅助功能。请问我是最好的,如果它实现IEnumerable&LT测试; T> 如果这样,这将在code样子?更新14:17 GMT + 10可能在一个解决方案扩展本...
我想,以确定是否一个通用对象类型(T)的方法类型参数是集合类型。我通常通过发送T作为一个Generic.List,但它可以是任何集合类型,因为这是用在辅助功能。
请问我是最好的,如果它实现IEnumerable&LT测试; T>
如果这样,这将在code样子?
更新14:17 GMT + 10可能在一个解决方案扩展本文(但是只适用于表< T>不是IEnumerable的< T>'?当它应该,如果列表导出S)
T currentObj;
//工作,如果currentObj的名单,其中,T>
。currentObj.GetType()GetGenericTypeDefinition()== typeof运算(名单<>)
//不工作,如果currentObj的名单,其中,T>
。currentObj.GetType()GetGenericTypeDefinition()== typeof运算(IEnumerable的<>)
解决方案
这将是最简单的检查。
如果(obj是ICollection的)
{
//自ICollection派生
}
其他
{
//不自ICollection派生
}
I want to determine if a generic object type ("T") method type parameter is a collection type. I would typically be sending T through as a Generic.List but it could be any collection type as this is used in a helper function.
Would I be best to test if it implements IEnumerable<T>?
If so, what would the code look like?
Update 14:17 GMT+10 Possibly extending on a solution here (however only works for List<T>'s not IEnumerable<T>'s when it should if List derives ?)
T currentObj;
// works if currentObj is List<T>
currentObj.GetType().GetGenericTypeDefinition() == typeof(List<>)
// does not work if currentObj is List<T>
currentObj.GetType().GetGenericTypeDefinition() == typeof(IEnumerable<>)
解决方案
This will be the simplest check..
if(Obj is ICollection)
{
//Derived from ICollection
}
else
{
//Not Derived from ICollection
}
相关推荐
最新文章