确定对象从集合类型派生 [英] Determine if object derives from collection type

查看:121
本文介绍了确定对象从集合类型派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,以确定是否一个通用对象类型(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
}

这篇关于确定对象从集合类型派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆