簡體   English   中英

如何在C#中使用參數和返回值通用實現接口方法

[英]How to implement a method, into interface, with parameter and returned value generic in C#

我想在C#中使用通用輸入參數和返回值實現接口。 目前,我已經定義了一個接口:

interface IResponseFormatter
{
    T formatResponseOptimizated<T>(T[] tagsValues);
}

之后,我嘗試實現一個具體的類:

public class FormatResponseInterpolatedData : IResponseFormatter

{
    ILog log = LogManager.GetLogger(typeof(HistorianPersistenceImpl));



    public Dictionary<string, List<object[]>> formatResponseOptimizated <Dictionary<string, List<object[]>>> (IHU_RETRIEVED_DATA_VALUES[] tagsValues)
    {
        log.Info("ENTER [formatResponseOptimizated] tagValues: " + tagsValues);
        Dictionary<string, List<object[]>> result = new Dictionary<string, List<object[]>>();

        // built data logic

        return result;
    }
}

我想了解我的錯以及如何使這種實現類型成為可能。

您正在非泛型接口中定義泛型方法。

TformatResponseOptimizated類型參數移動到IResponseFormatter類型參數,並在實現類中提供規范:

interface IResponseFormatter<T> {
    // Follow C# naming conventions: method names start in an upper case letter
    T FormatResponseOptimizated(T[] tagsValues);
}
public class FormatResponseInterpolatedData
     : IResponseFormatter<Dictionary<string,List<object[]>>> {
    public Dictionary<string,List<object[]>> FormatResponseOptimizated(Dictionary<string,List<object[]>>[] tagsValues) {
        ...
    }
}

請注意,對於單個類型參數TFormatResponseOptimizated的返回類型必須與作為其參數T[]的數組元素的類型匹配。 如果兩者應該不同,則在兩種類型的接口上參數化,例如,參數為TArgTRetTRet

我展示了更正的實現:

介面

interface IResponseFormatter<T,U>
{
    T formatResponseOptimizated(U[] tagsValues);
}

實作課程:

public class FormatResponseInterpolatedData : IResponseFormatter<Dictionary<string, List<object[]>>, IHU_RETRIEVED_DATA_VALUES>

{

    public Dictionary<string, List<object[]>> formatResponseOptimizated(IHU_RETRIEVED_DATA_VALUES[] tagsValues)
    {
        // implemented data logic
    }
}

謝謝

暫無
暫無

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

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