![](/img/trans.png)
[英]C# The is no implicit reference conversion from 'B' to 'A' using Generics
[英]How to resolve a “No implicit reference conversion” issue when using Generics & Interfaces
有什么想法可以解決以下錯誤或重構我的方法以避免它嗎?
我定義了以下接口:
public interface IApiClient<TConfig, TOrder>
where TConfig : IApiClientConfiguration
where TOrder : IApiClientOrder
{
TConfig Configuration { get; }
IApiClientOrderConverter<TOrder> GetOrderConverter();
Task<IEnumerable<TOrder>> GetNewOrdersAsync();
}
public interface IApiClientOrderConverter<TOrder>
where TOrder : IApiClientOrder
{
WarehouseOrder ClientOrderToWarehouseOrder(TOrder order);
}
使用基於它的實現:
public class SolidApiClient : IApiClient<SolidApiClientConfiguration, SolidOrder>
{
public SolidApiClientConfiguration Configuration { get; }
public IApiClientOrderConverter<SolidOrder> GetOrderConverter()
{
...
}
public async Task<IEnumerable<SolidOrder>> GetNewOrdersAsync()
{
...
}
}
有一個 function 我正在嘗試使用以下簽名調用:
protected async Task ProcessClients<T>(IEnumerable<IApiClientConfiguration> clientConfigs)
where T : IApiClient<IApiClientConfiguration, IApiClientOrder>
{
...
}
我試圖這樣稱呼它:
await ProcessClients<SolidApiClient>(clientsConfig);
但由於以下錯誤,我無法使用 SolidApiClient 進行通用調用:
錯誤 CS0311 類型“SolidApiClient”不能用作泛型類型或方法“Function.ProcessClients(string, IEnumerable)”中的類型參數“T”。 沒有從“SolidApiClient”到“IApiClient<IApiClientConfiguration, IApiClientOrder>”的隱式引用轉換。
我已經看到這里發布了許多類似的不同問題,但我還沒有設法從我迄今為止找到的答案中找到解決方案,所以我會伸出援手,以防有人發現我錯過的方法.
我也嘗試了我的方法的一些變體,但似乎只是將問題轉移到代碼的不同部分,所以相信我必須對接口類和 generics 使用有缺陷的方法。
根據@pinkfloydx33 的建議,我改變了使用抽象基類的方法。
作為獎勵,遠離接口和 generics 大大簡化了解決方案。 在我的特定場景中,使用接口和 generics 是一個糟糕的選擇。
要使用ProcessClients
,它需要定義與IApiClient<...>
相同的通用約束;
ProcessClients<TClient, TConfig, TOrder>
(IEnumerable<TConfig> clientConfigs)
where TClient : IApiClient<TConfig, TOrder>
where TConfig : IApiClientConfiguration
where TOrder : IApiClientOrder
這感覺就像代碼氣味。 隱藏這種復雜性的另一種方法是定義更多的接口,這樣您就不需要一直引用通用接口;
interface IApiClient {}
interface IApiClient<T> : IApiClient {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.