有没有办法在 C# 3.0 中实现泛型类型的协变?
这已经在C# 4.0中引入了,但是在c# 3.0中有没有办法实现这一点呢?
例如,考虑以下代码:
class Base
{
}
class Derived1 : Base
{
}
class Derived2 : Base
{
}
class User<T> where T : Base
{
}
class User1 : User<Derived1>
{
}
现在,我想要一个 User
列表,其中可以存储 User
以及 < code>User
List<User<Base>> users = new List<User<Base>>();
users.Add(new User1());
有什么想法吗?
This has been introduced in C# 4.0, but is there a way to achieve this in c# 3.0?
For e.g., consider the following code:
class Base
{
}
class Derived1 : Base
{
}
class Derived2 : Base
{
}
class User<T> where T : Base
{
}
class User1 : User<Derived1>
{
}
Now, I would like to have a list of User<T>
, in which I can store User<Derived1>
as well as User<Derived2>
, but the following code fails to compile in C# 3.0:
List<User<Base>> users = new List<User<Base>>();
users.Add(new User1());
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不仅没有好的解决方法,而且您的代码也无法在 C# 4.0 中工作 - 只有接口和委托支持差异,因此您永远无法将
User
视为User
代码>用户<基础>。Not only is there no good workaround, but your code also won't work in C# 4.0 - only interfaces and delegates support variance, so you will never be able to treat a
User<Derived>
as aUser<Base>
.最简单的方法可能是使用 ArrayList 或 List
The simplest approach is probably to use an
ArrayList
orList<object>
and handle the casting yourself. There's no elegant way to do it in C# 3.