【发布时间】:2013-12-05 20:21:33
【问题描述】:
我正在使用一个 Web 服务,它返回两种完全相同但被称为两种不同事物的类型(是的,我知道很棒的 API...)。一种称为SearchKMQueryResponse,另一种称为TopSolutionsKMQueryResponse。我将这些类型的输出映射到我自己的模型类中,并且必须使用两种采用不同参数类型但返回相同类型的方法。这两种 API 类型继承了object 类型,因此我不能将基类型作为参数传入。他们不通过 API 公开接口,所以我也搞砸了。
那么有没有一个优雅的解决方案来停止在下面的代码中重复自己? ...
编辑:我使用 .Net v3.5 来解决这个问题。
public static KmSearchResponse Map(SearchKMQueryResponse response)
{
if (response == null)
{
return null;
}
else
{
var myResponse = new KmSearchResponse()
{
CountTotal = long.Parse(response.model.instance.resultlist.resultlist[0].Value),
Message = response.message,
Status = (MyProject.Model.StatusType)response.status,
};
for (var startID = 2; startID < (myResponse.CountTotal * 5); startID += 5)
{
myResponse.Results.Add(
KmSearchResponseResultsMapper.Map(
response.model.instance.resultlist.resultlist, startID)
);
}
myResponse.Count = myResponse.Results.Count;
return myResponse;
}
}
public static KmSearchResponse Map(TopSolutionsKMQueryResponse response)
{
if (response == null)
{
return null;
}
else
{
var myResponse = new KmSearchResponse()
{
CountTotal = long.Parse(response.model.instance.resultlist.resultlist[0].Value),
Message = response.message,
Status = (MyProject.Model.StatusType)response.status,
};
for (var startID = 2; startID < (myResponse.CountTotal * 5); startID += 5)
{
myResponse.Results.Add(
KmSearchResponseResultsMapper.Map(
response.model.instance.resultlist.resultlist, startID)
);
}
myResponse.Count = myResponse.Results.Count;
return myResponse;
}
}
【问题讨论】:
-
如果该类型非常小,您可以轻松编写包装器
-
SearchKMQueryResponse 和 TopSolutionsKMQueryResponse 是您客户端的一些自动生成的类吗?
-
没关系,你已经得到了我脑海中的答案:CodeCaster
标签: c# .net generics types .net-3.5