泛型集合里面能装泛型类吗

yizhixiaozhu 2011-05-25 11:21:29
比如我有个泛型类:

class aaa<T>{}

然后我想把这些实例化的类加入到List<T>里面去:

aaa<int> a = new aaa<int>();

aaa<double> b = new aaa<double>();

aaa<string> c = new aaa<string>();

我想把上面的3个实例都add到这个List<T> 里面去,

这个该怎么加?

因为 在实例化 List<aaa<int>> lit = new List<aaa<int>>()
这个地方需要要指定aaa这个泛型类的T的类型,但是我的这些T可能不一样,

能加吗,
...全文
273 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2011-05-25
  • 打赏
  • 举报
回复
C# 4 支持泛型的协变,但是用起来要格外小心。
threenewbee 2011-05-25
  • 打赏
  • 举报
回复
没看清lz的意思。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Base> list = new List<Base>();
list.Add(new A<int>());
}
}

class Base { };

class A<T> : Base
{
public override string ToString()
{
return this.GetType().ToString();
}
}
}
我姓区不姓区 2011-05-25
  • 打赏
  • 举报
回复
[Quote=引用楼主 yizhixiaozhu 的回复:]
比如我有个泛型类:

class aaa<T>{}

然后我想把这些实例化的类加入到List<T>里面去:

aaa<int> a = new aaa<int>();

aaa<double> b = new aaa<double>();

aaa<string> c = new aaa<string>();

我想把上面的3个实例都add到这个List<T> 里面去,……
[/Quote]
不能,如果你这样做就违背了泛型中类型安全的原则,ArrayList就是这么使的……
兔子-顾问 2011-05-25
  • 打赏
  • 举报
回复
如果类型不确定。无法创建。你只能用ArrayList
threenewbee 2011-05-25
  • 打赏
  • 举报
回复
List<aaa<T>>
Damon_lan 2011-05-25
  • 打赏
  • 举报
回复
呵呵~。泛型类 还没用过!!~
bios8086 2011-05-25
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 ohkuy 的回复:]

你放在Dictionary<>里不就可以了,
没有什么隐患
[/Quote]
貌似很多人都喜欢这个
ohkuy 2011-05-25
  • 打赏
  • 举报
回复
你放在Dictionary<>里不就可以了,
没有什么隐患

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧