如何在 C# 中对开放类型进行泛型多态性? [英] How to do generic polymorphism on open types in C#?

查看:24
本文介绍了如何在 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# 中对开放类型进行泛型多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆