在 C# 中传递泛型作为泛型类型参数

Jay*_*Jay 5 c# generics type-parameter

我在 C# 中对泛型做了一个小实验,我遇到了一个问题,我想将泛型类型作为类型参数传递,并带有约束来实现我不知道其类型的泛型接口。

这是我的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        interface IGenericCollection<T>
        {
            IEnumerable<T> Items { get; set; }
        }

        abstract class GenericCollection<T> : IGenericCollection<T>
        {
            public IEnumerable<T> Items { get; set; }
        }

        //This class holds a generic collection but i have to ensure this class
        //implements my IGenericCollection interface. The problem here is that
        //i dont know which type TGenericCollection is using and so i am unable to
        //pass this information to the constraint. 

        class CollectionOwner<TGenericCollection>
           where TGenericCollection : IGenericCollection< dont know ... >
        {
            protected TGenericCollection theCollection = default(TGenericCollection);
        }

        static void Main(string[] args)
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里阅读了几篇文章,所有文章都告诉我由于 C# 和 CLR 的限制,这是不可能的。但这样做的正确方法是什么?

Jen*_*ter 1

也许你应该使用另一个类型参数:

class CollectionOwner<TGenericCollection, T2>
   where TGenericCollection : IGenericCollection<T2>
   where T2 : class
{
    protected TGenericCollection theCollection = default(TGenericCollection);
}
Run Code Online (Sandbox Code Playgroud)

您需要这套衣服吗?