我在C#中泛型做了一點實驗,並且遇到了一個問題,我想通過泛型類型作爲帶有約束的類型參數來實現泛型類型的接口不知道。在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的限制。但是,這樣做的正確方法是什麼?