我在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)
{
}
}
}
我已经阅读了这里的几篇文章,所有的文章都告诉我由于C#和CLR的限制是不可能的。但是正确的方法是什么呢?