簡體   English   中英

當接口有多個通用參數時,如何解決“無法隱式轉換[type]到[interface]”錯誤?

[英]How do I solve the “cannot implicitly convert [type] to [interface]” error when the interface has multiple generic parameters?

我有以下接口:

public interface IQueryHandler<in TQuery, out TResult> where TResult : class 
                                                where TQuery : IQuery<TResult>
{
    TResult Handle(TQuery query);
}

public interface IQuery<TResult> // Doesn't require anything special, just used to guarantee that IQueryHandlers get the right parameters.
{
}

它旨在由IQueryHandlers ,它將接收IQuery<TResult> ,它定義一個返回TResult類型對象的查詢。 然后IQueryHandlerHandle方法返回一個TResult

我在DataQueryHandlers類上實現了接口:

public class DataQueryHandlers : IQueryHandler<GetDataById, SomeData>
{
    private IDataSource source;

    public DataQueryHandlers(IDataSource source)
    {
        this.source = source
    }

    public SomeData Handle(GetDataById query)
    {
        // Get the data here and return SomeData object
    }
}

其中SomeData是數據實體, GetDataByIdIQuery<SomeData>

但是,當我嘗試實例化一個特定的實例時:

private IQueryHandler<IQuery<SomeData>, SomeData> dataQueryHandlers;
private IDataSource source;

source = new DataSource(); // some data provider

dataQueryHandlers = new DataQueryHandlers(datasource); // This line won't compile

我收到編譯器錯誤:

無法將類型DataQueryHandlers隱式轉換為IQueryHandler<IQuery<SomeData>, SomeData> 存在顯式轉換(您是否錯過了演員?)

我確定這是一個協變/逆變相關的問題,但我沒有看到不匹配的位置。 我的輸入/輸出通用修飾符有問題嗎? 從某種意義上說,我試圖從根本上做錯嗎? 這里錯過了一些明顯的“ 魚頭發 ”情景嗎?

您應該將派生類更改為通用類以便能夠執行此操作。 把它改成這個:

public class DataQueryHandlers<in TQuery, out TResult> : IQueryHandler<TQuery, TResult> where TResult : class where TQuery : IQuery<TResult>
{
    private IDataSource source;

    public DataQueryHandlers(IDataSource source)
    {
        this.source = source
    }

    public TResult Handle(TQuery query)
    {
        // Get the data here and return TResult object
    }
}

有關Generic Classes的更多信息,您可以找到MSDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM