有没有办法在 C# 3.0 中实现泛型类型的协变?

发布于 2024-08-28 02:15:54 字数 531 浏览 4 评论 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,但以下代码无法在 C# 3.0 中编译:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

失眠症患者 2024-09-04 02:15:54

不仅没有好的解决方法,而且您的代码也无法在 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 a User<Base>.

萌梦深 2024-09-04 02:15:54

最简单的方法可能是使用 ArrayList 或 List并自行处理转换。在 C# 3 中没有优雅的方法来做到这一点。

The simplest approach is probably to use an ArrayList or List<object> and handle the casting yourself. There's no elegant way to do it in C# 3.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文