我有以下类,我使用它生成一个请求对象并序列化响应以获取JSON字符串。类的定义如下
PortfolioResponse& StocksInfo 类是为了提及目的,因为它们包含很多我无法在这里写的字段。
[DataContract]
public class BaseInfoRequest
{
[DataMember]
public string Token { get; set; }
}
[DataContract]
public class StocksInfoRequest : BaseInfoRequest
{
[DataMember]
public string SomeKey { get; set; }
}
[DataContract]
public class PortfolioInfoRequest : BaseInfoRequest
{
[DataMember]
public string PortfolioId { get; set; }
[DataMember]
public string SomeKey { get; set; }
}
[DataContract]
public class StocksInfoResponse
{
[DataMember(Name = "success")]
public bool Success { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "stocks")]
public StocksInfo StocksInfo { get; set; }
[DataMember(Name = "pfolio")]
public PortfolioResponse PortfolioInfo { get; set; }
}
public class PortfolioResponse
{
}
public class StocksInfo
{
}
现在,为了从项目中获取来自不同其他类和服务的数据,我在下面使用了两种方法,比如说样本
private string GetsStocksInformation(StocksInfoRequest request)
{
var response = new StocksInfoResponse();
if (ValidateRequestToken(request) || string.IsNullOrWhiteSpace(request.SomeKey))
{
response.Message =
GetsResponse().ErrorMessage;
return JsonConvert.SerializeObject(response);
}
response.StocksInfo = GetsStocksInfo(request);
response.Success = true;
return JsonConvert.SerializeObject(response);
}
private string GetsPortfolioInformation(PortfolioInfoRequest request)
{
var response = new StocksInfoResponse();
if (!ValidateRequestToken(request) || string.IsNullOrWhiteSpace(request.SomeKey) ||
string.IsNullOrWhiteSpace(request.PortfolioId))
{
response.Message =
GetsResponse().ErrorMessage;
return JsonConvert.SerializeObject(response);
}
response.PortfolioInfo = GetsPortfolioInfo(request.SomeKey, request.PortfolioId);
response.Success = true;
return JsonConvert.SerializeObject(response);
}
现在,如果仔细观察,除条件
外,两种方法几乎相同if(ValidateRequestToken(request)|| string.IsNullOrWhiteSpace(request.SomeKey))&&
response.StocksInfo = GetsStocksInfo(request);
除了上述两种,这两种方法或多或少都是相同的。 ValidateRequestToken 的定义在
之下 private bool ValidateRequestToken(BaseInfoRequest request)
{
return true;
}
如何组合这两种方法来创建通用方法?