我在用返回类型的泛型方法转换为泛型集合类型时遇到了困难。
在this answer中明确写明是为了避免
打开通用类型
但是在this answer中说明了如何执行此操作。
我承认,我使用泛型来避免为三种不同的返回类型编写相同代码的三倍。现在,编译器告诉我,
并非所有代码路径都返回值
调用者方法调用者示例:
public ObservableCollection<LoadedJockey> Jockeys { get; private set; }
Jockeys = await _updateDataService.UpdateDataAsync(Jockeys, DataUpdateModules.JPlFrom, DataUpdateModules.JPlTo, "updateJockeysPl");
我的通用方法如下:
public async Task<ObservableCollection<T>> UpdateDataAsync<T>(ObservableCollection<T> genericCollection, int idFrom, int idTo, string jobType) where T : IConvertible
{
//variables reset here
_loopCounterProgressBar = 0;
_idFromProgressBar = idFrom;
_idToProgressBar = idTo;
if (typeof(T) == typeof(LoadedHorse))
{
//do something here
}
else if (typeof(T) == typeof(LoadedJockey))
{
//do something here
}
else if (typeof(T) == typeof(LoadedHistoricalRace))
{
//do something here
}
//initial
SemaphoreSlim throttler = new SemaphoreSlim(_degreeOfParallelism);
List<Task> tasks = new List<Task>();
TokenSource = new CancellationTokenSource();
CancellationToken = TokenSource.Token;
OnProgressBarTick();
//run loop
for (int i = idFrom; i < idTo; i++)
{
int id = i;
tasks.Add(Task.Run(async () =>
{
try
{
if (CancellationToken.IsCancellationRequested)
return;
await throttler.WaitAsync(TokenSource.Token);
if (jobType.Contains("Horses"))
{
await //call service method
}
else if (jobType.Contains("Jockeys"))
{
await //call service method
}
else if (jobType.Contains("Historic"))
{
await //call service method
}
}
catch (Exception e)
{
}
finally
{
_loopCounterProgressBar++;
EventHandler<UpdateBarEventArgs> progressBarTick = _updateProgressEventHandler;
OnProgressBarTick();
throttler.Release();
}
}));
}
try
{
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
{
}
finally
{
//save results in file when finish
}
}
//here I wanted to return some result depending on T
if (typeof(T) == typeof(LoadedHorse))
{
return (ObservableCollection<T>)Convert.ChangeType(Horses, typeof(ObservableCollection<T>));
}
else if (typeof(T) == typeof(LoadedJockey))
{
return (ObservableCollection<T>)Convert.ChangeType(Jockeys, typeof(ObservableCollection<T>));
}
else if (typeof(T) == typeof(LoadedHistoricalRace))
{
return (ObservableCollection<T>)Convert.ChangeType(Races, typeof(ObservableCollection<T>));
}
}
如您所见,我希望收到3种不同的 T 。而且我认为我涵盖了所有内容。我的解决方案基于this example。我猜想我可能将Convert
的类型错误地写为T
,但是我不应该怎么做。
答案 0 :(得分:0)
按照 Camilo Terevinto 的建议,我在if else
链else { throw new ArgumentException() }
的末尾添加了内容,编译器对此感到满意。