2012-12-13 126 views
1

我有一個C#泛型 - 類實現其他泛型類

public class A<T> where T : IBase 
{ 
    //Does something 
} 

我需要表現得像類集合的第二類A

public class B<A<T>> : IEnumerable<A<T>> where T : IBase 
{ 
} 

的問題是,我不希望創建類如

public class B<A<MyCustomObjectP>> : IEnumerable<A<MyCustomObjectP>> 
{ 
} 

public class C<A<MyCustomObjectQ>> : IEnumerable<A<MyCustomObjectQ>> 
{ 
} 

等等..我想讓CustomObject成爲泛型類型參數th在執行IBase。

我發現,即使這樣做是違法的:

public class B<T, U> : IEnumerable<T> where T : A<U> where U : IBase 
{ 
} 

我怎麼能實現這種類型的行爲,如果這是非法的?有沒有更好的設計模式可以幫助?

回答

1

IBase約束被定義在A<T>,所以必須再次對所有泛型類,即要使用A<U>被定義(使用UTA<T>類的定義來區分,但它可以叫什麼)。你應該能夠簡單地做:

public class B<T> : IEnumerable<A<T>> where T : IBase { ... } 
+0

嘿。那很簡單。我正在推翻它。謝謝!這似乎有伎倆。 :) – Harsha

+0

不客氣:) –

0

你寫,你需要表現得像A類的集合二等

既然你有其他類(如B)從IBase繼承爲好,這要添加,可以使採集的IBase集合。

因此該解決方案是這樣的(請注意,我用List,但你可以很容易地替換由IEnumerable - 但你必須要實現像.Add自己的方法):

void Main() 
{ 
    var items = new CollectionOf<IBase>(); // create list of IBase elements 
    items.Add(new A() { myProperty = "Hello" }); // create object of A and add it to list 
    items.Add(new B() { myProperty = "World" }); // create object of B and add it to list 
    foreach(var item in items) 
    { 
     Console.WriteLine(item.myProperty); 
    } 
} 

// this is the collection class you asked for 
public class CollectionOf<U>: List<U> 
where U: IBase 
{ 
    // collection class enumerating A 
    // note you could have used IEnumerable instead of List 
} 

public class A: IBase 
{ 
    // class A that implements IBase 
    public string myProperty { get; set; } 
} 

public class B: IBase 
{ 
    // class B that implements IBase too 
    public string myProperty { get; set; } 
} 

public interface IBase { 
    // some inteface 
    string myProperty { get; set; } 
}