![](/img/trans.png)
[英]Generic inference of type parameter with constraint to other type parameter
[英]Generic Type Parameter Inference
我在中間層有一個方便的集合,該集合用於收集屬於父事物的子事物。
public class ChildCollection<TParent, TChild>
{
public IEnumerable<TChild> GetChildren();
etc.
}
在界面中,我有一個方便的網格,可以顯示ChildCollection <TParent,TChild>的內容,並讓用戶對其進行處理。
public abstract class ChildCollectionGrid<TCollection, TParent, TChild> : MyGridControl
where TCollection : ChildCollection<TParent, TChild>
{
public abstract TCollection Collection;
etc.
}
繼承此類以使網格與Widget上的Waffles一起使用時,最終看起來像這樣。
public class WidgetWafflesGrid : ChildCollectionGrid<WidgetWafflesCollection, Widget, Waffle>
這有點多余。 WidgetWaffleCollection 是 ChildCollection <Widget,Waffle>。 在指定了第一個泛型類型參數之后,該類將不會編譯,除非您確切指定另外兩個。
在編譯器可以推斷其他兩種類型的情況下,是否有更漂亮的方法來完成此操作? 我知道我很挑剔,但理想情況下,我希望類聲明如下:
public class WidgetWafflesGrid : ChildCollectionGrid<WidgetWafflesCollection>
謝謝你的幫助!
不,沒有。 通用參數推斷僅適用於方法。
為什么從您的收藏中獲取? 保持像這樣:
public abstract class ChildCollectionGrid<TParent, TChild> : MyGridControl
{
public abstract ChildCollection<TParent, TChild> Collection;
etc.
}
public class WidgetWafflesGrid : ChildCollectionGrid<Widget, Waffle>
{
}
處理帶有泛型的集合中的繼承的唯一方法是使用Collection<TCollection,TChild> : where TCollection : Collection<TCollection,TChild> { }
模式。
這是一個具體的例子
public abstract class Collection<TCollection, TChild>
where TCollection : Collection<TCollection, TChild>, new()
{
protected Collection()
{
List=new List<TChild>();
}
protected List<TChild> List { get; set; }
public TCollection Where(Func<TChild, bool> predicate)
{
var result=new TCollection();
result.List.AddRange(List.Where(predicate));
return result;
}
public void Add(TChild item) { List.Add(item); }
public void AddRange(IEnumerable<TChild> collection) { List.AddRange(collection); }
}
public class Waffle
{
public double Temperature { get; set; }
}
public class WafflesCollection : Collection<WafflesCollection, Waffle>
{
public WafflesCollection BurnedWaffles
{
get
{
return Where((w) => w.Temperature>108);
}
}
}
class Program
{
static void Main(string[] args)
{
WafflesCollection waffles=new WafflesCollection();
// Count = 3
waffles.Add(new Waffle() { Temperature=100 });
waffles.Add(new Waffle() { Temperature=120 });
waffles.Add(new Waffle() { Temperature=105 });
var burned=waffles.BurnedWaffles;
// Count = 1
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.