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# 中对开放类型进行泛型多态性?
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
