如何声明一个对象,该对象是泛型类型的列表的列表 [英] How to declare an object that is a list of lists of a generic type

查看:202
本文介绍了如何声明一个对象,该对象是泛型类型的列表的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以声明一个对象是一个 <泛型类型列表的列表。
所以有点像 private List< List< T>> outerList = new List< List< T>>(); ,但是一个实际编译的语句。

I / strong>希望像这样使用动态: private List< List< dynamic>> list2 = new List< List< dynamic>>(); ,因为我想要安全类型。



能够:

  foreach(列表< T> innerList in outerList)
{
foreach(T项目在innerList)
{
doSomethingTo(item);


理想情况下,我想声明一个继承的类从列表< List< T>>< / code>< / p>




strong>编辑:



我应该已经更清楚了。内部列表必须能够具有不同的类型。所以一个内部列表可能是 List< string> 和另一个 List< int>






进一步编辑

关注 @ErikE 的请求已被重新编写

当然,您可以将其定义为泛型类:

  public class Foo< T> :List< List< T>> 
{

}

然后有一个通用方法处理其中之一:

  public void Process< T>(Foo< T> outerList)
{$ b $ (foreList中的List< T> innerList)
{
foreach(innerList中的T item)
{
doSomethingTo(item);
}
}
}

当然 doSomethingTo 然后也需要是通用的。


我应该更清楚了。内部列表必须能够具有不同的类型。所以一个内部列表可能是 List< string> 和另一个 List< int>


是的,你应该清楚一点。在 List< string> List< int> 之间没有继承关系,可以将它们存储为单个类型安全的外部收集。你必须求助于 List< object> List< dynamic> ,或者找到一个不同的数据结构您的需求。


Is it possible to declare an object that is is a list of lists of a generic types. So a little like private List<List<T>> outerList = new List<List<T>>(); but a statement that actually compiles.

I do not want to use dynamics like so: private List<List<dynamic>> list2 = new List<List<dynamic>>(); as I would like type safety.

I'd kind of like to be able to:

foreach(List<T> innerList in outerList)
{
    foreach(T item in innerList)
    {
        doSomethingTo(item);
    }
}

Ideally I'd like to declare a class that inherits from the List<List<T>>


EDIT:

I probably should have been clearer. The inner lists must be able to have different types. so one inner list may be List<string> and another List<int>


FURTHER EDIT:

Following @ErikE's request the question has been reworded here.

解决方案

Sure, you can define that as a generic class:

public class Foo<T> : List<List<T>>
{

}

and then have a generic method that processes one of them:

public void Process<T>(Foo<T> outerList)
{
    foreach(List<T> innerList in outerList)
    {
        foreach(T item in innerList)
        {
            doSomethingTo(item);
        }
    }
}

of course doSomethingTo would then need to be generic as well.

I probably should have been clearer. The inner lists must be able to have different types. so one inner list may be List<string> and another List<int>

Yes, you should have been clearer. There's no inheritance relationship between List<string> and List<int> that would allow you to store them in a single type-safe outer collection. You would have to resort to List<object> or List<dynamic>, or find a different data structure that meets your needs.

这篇关于如何声明一个对象,该对象是泛型类型的列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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