How to do generic polymorphism on open types in C#?(如何在 C# 中对开放类型进行泛型多态性?)
问题描述
我有一个类似的界面:
interface IFoo<in T> {
...
}
并且我希望拥有这些类的集合不为所有集合元素强制使用特定的通用参数,例如:
And I want to have a collection of those classes WITHOUT forcing a specific generic parameter for all collection elements, like:
class IFooCollection {
List<IFoo<?>> _items;
public IFooCollection(List<IFoo<?>> items)
{
_items = items;
}
...
}
推荐答案
既然你不想强制一个特定的类型,那就做一个abstract class
或者一个interface
这样:
Since you don't want to force a specific type, make an abstract class
or an interface
this way:
interface IFoo { }
并在特定类型的 Foo 中继承它(使用泛型参数),例如:
And inherit it in your type-specific Foo (with generic parameters), like:
interface IFoo<T> : IFoo {}
这样你就可以有一个 List<IFoo>
并添加 IFoo<T>
代替.
This way you can just have a List<IFoo>
and add IFoo<T>
instead.
更多示例:
class FooCollection {
private List<IFoo> _collection;
public FooCollection()
{
_collection = new List<IFoo>();
}
public void Add(IFoo foo)
{
_collection.Add(foo);
}
public void Remove(IFoo foo)
{
_collection.Remove(foo);
}
}
这篇关于如何在 C# 中对开放类型进行泛型多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中对开放类型进行泛型多态性?


基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01