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# 中对开放类型进行泛型多态性?
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
