如何在C#中对开放类型进行通用多态? [英] 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;
}
...
}
推荐答案
由于您不想强制使用特定类型,因此请创建抽象类
或接口
这样:
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#中对开放类型进行通用多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文