![](/img/trans.png)
[英]How can I implement a factory to return a type that implements a generic interface, without knowing the generic type ahead of time?
[英]How can I constrain a generic type to implement a generic interface?
我正在使用API的C#庫,下面進行了簡化:
// GET /foos
{
"data": [
{ FooResource },
{ Fooresource },
...
]
}
// GET /bars
{
"data": [
{ BarResource },
{ BarResource },
...
]
}
我希望圖書館的用戶能夠指定他們要使用的通用集合。 到現在為止還挺好。
class ApiResources<T, TCollection> where TCollection : ICollection<T>
{
public TCollection Data { get; set; }
}
但是,我希望在實例化客戶端單例時指定它(在這種情況下, IFoo
和IBar
是定義Foo和Bar資源中各種鍵的接口)
class ApiClient<TFoo, TBar, TCollection>
where TFoo : IFoo
where TBar : IBar
where TCollection : ???
{
TCollection<TFoo> GetFoos()
{
ApiResources<TFoo, TCollection> resources = // make API call to get Foos
return resources.Data;
}
TCollection<TBar> GetBars()
{
ApiResources<TBar, TCollection> resources = // make API call to get Bars
return resources.Data;
}
}
我該怎么做呢? 我得到了There is no boxing conversion or type parameter conversion from 'TCollection' to 'ICollection<TFoo>'
錯誤, There is no boxing conversion or type parameter conversion from 'TCollection' to 'ICollection<TFoo>'
。 我基本上想擁有TCollection : ICollection<T>
而無需在ApiClient
類定義中定義T
編輯:
我希望能夠寫:
var client = new ApiClient<Foo, Bar, List>(); // List<T> for any T???
List<Foo> foos = client.GetFoos();
List<Bar> bars = client.GetBars();
您的類ApiClient
甚至沒有使用ApiResource
,因此您不能將ApiResource
的TCollection
ApiClient
約束為ApiClient
的TCollection
ApiResource
(不存在)。 所以我建議你做了同樣的約束ApiClient
,那你做ApiResources
:
class ApiClient<TFoo, TBar, T, TCollection> [...] where TCollection : ICollection<T>
用法:
var x = new ApiClient<Foo, Bar, SomeClass, Collection<SomeClass>>().GetFoos();
或者您將方法設為通用 ,如下所示:
TCollection GetFoos<T, TCollection> where T : TFoo where TCollection : ICollection<T>()
{
ApiResources<TFoo, TCollection> resources = // make API call to get Foos
return resources.Data;
}
用法:
var x = new ApiClient<Foo, Bar>().GetFoos<SomeClass, Collection<SomeClass>>();
但是也許我完全理解您的問題。 很難確定要達到的目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.