如何在 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) {
        ...
    }
}

请注意,对于单个类型参数T返回类型FormatResponseOptimizated必须与它作为其参数的数组元素的类型匹配 T[] 。如果两者应该不同,请在两种类型上参数化您的接口,例如,TArg用于参数,TRet用于返回。

我展示了更正的实现:

接口

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
    }
}

谢谢

最新更新