2013-03-08 338 views
4

我在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的限制。但是,這樣做的正確方法是什麼?

回答

1

也許你應該另一種類型的參數:

class CollectionOwner<TGenericCollection, T2> 
    where TGenericCollection : IGenericCollection<T2> 
    where T2 : class 
{ 
    protected TGenericCollection theCollection = default(TGenericCollection); 
} 

這是否會適合你需要什麼?

1

我不認爲這裏有一個問題,只是增加一個泛型參數到你的主階級:

class CollectionOwner<T,TGenericCollection> 
      where TGenericCollection : IGenericCollection<T> 
     { 
      protected TGenericCollection theCollection = default(TGenericCollection); 
     } 
1

您可以在第二個泛型參數添加到實現類。下面的靜態Example方法顯示了一個例子。

public interface ITest<T> 
{ 
    T GetValue(); 
} 

public class Test<T, U> where T : ITest<U> 
{ 
    public U GetValue(T input) 
    { 
     return input.GetValue(); 
    } 
} 

public class Impl : ITest<string> 
{ 
    public string GetValue() 
    { 
     return "yay!"; 
    } 

    public static void Example() 
    { 
     Test<Impl, string> val = new Test<Impl,string>(); 
     string result = val.GetValue(new Impl()); 
    } 
} 
0

使用第二泛型參數是一個選項4肯定是我已經想用但對於這個

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

    class ConcreteCollection : GenericCollection<string> 
    { 

    } 

    static void Main(string[] args) 
    { 
     // will constraint fail here ? 
     CollectionOwner<int,ConcreteCollection> o = new CollectionOwner(int, ConcreteCollection); 
    }