我发现我重复了这段代码好几次,我希望能得到一些帮助来正确地重构它。我该如何传递我希望从电话中回复的类型列表?
masterData.PatternData = await GetMeetingData();
masterData.PatternDataDays = await GetMeetingDays();
private async Task<List<MeetingPatternData>> GetMeetingData()
{
var retVal = new List<MeetingPatternData>();
try
{
var client = ClientFactory.CreateClient("ServerAPI");
retVal = await client.GetFromJsonAsync<List<MeetingPatternData>>("MeetingTimeManager/GetPatterns");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
return retVal;
}
private async Task<List<MeetingPatternDays>> GetMeetingDays()
{
var retVal = new List<MeetingPatternDays>();
try
{
var client = ClientFactory.CreateClient("ServerAPI");
retVal = await client.GetFromJsonAsync<List<MeetingPatternDays>>("MeetingTimeManager/GetDays");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
return retVal;
}
变量部分是返回类型和URI,因此如果您这样声明方法:
private async Task<List<T>> Get<T>(string requestUri)
{
try
{
var client = ClientFactory.CreateClient("ServerAPI");
return await client.GetFromJsonAsync<List<T>>(requestUri);
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
return new List<T>();
}
然后你可以这样打电话:
masterData.PatternData = await Get<MeetingPatternData>("MeetingTimeManager/GetPatterns");
masterData.PatternDataDays = await Get<MeetingPatternDays>("MeetingTimeManager/GetDays");
我已经删除了这个部分:
var retVal = new List<MeetingPatternData>();
因为您不必要地分配List
。
您可能还应该返回IEnumerable<T>
,而不是List<T>
,这是基于使用执行该工作所需的最严格类型的理念,除非调用者需要处理返回的数据。