[英]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;
}
}
我想了解我的錯以及如何使這種實現類型成為可能。
您正在非泛型接口中定義泛型方法。
將T
從formatResponseOptimizated
類型參數移動到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
為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
}
}
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.