如何通用这个? [英] how to generic this?
问题描述
我怎么能拥有那个func泛型?
how can i have that func generic?
最好将是一个任务(没有返回值)和任务< ; T> :)
the best will be a task (with no return val) and task<T> :)
谢谢
internal async Task<int> DoIsBusyAsync2(Func<Task<int>> func)
{
if (this.IsBusy)
return -1;
try
{
this.IsBusy = true;
return await Task.Run<int>(() => {return func(); });
}
catch (System.Exception e)
{
//System.Diagnostics.Debug.WriteLine(e);
}
finally
{
this.IsBusy = false;
}
return -1;
}
推荐答案
我不确定关于您是否一起询问或发布问题和答案,但您可以做的是在您的方法中添加泛型类型参数,如:
I am not sure about whether you have asked or posting a question and answer together, but what you can do is add a generic type parameter to your method like:
internal async Task<TResult> DoIsBusyAsync2<TResult>(Func<Task<TResult>> func)
{
TResult result = null;
if(this.IsBusy)
返回-1;
尝试
{
this.IsBusy = true;
result = await Task.Run< TResult>(()=> {return func();});
}
catch(System.Exception e)
{
//System.Diagnostics.Debug.WriteLine(e);
}
最后
{
this.IsBusy = false;
}
返回结果;
if (this.IsBusy) return -1; try { this.IsBusy = true; result = await Task.Run<TResult>(() => {return func(); }); } catch (System.Exception e) { //System.Diagnostics.Debug.WriteLine(e); } finally { this.IsBusy = false; } return result;
现在调用它时,我们可以指定$返回任务的类型b $ b Func<> 委托传递给它就像:
Now when calling it, we can specify the type of which the Task would be returned by the Func<> delegate passed to it like:
var task = DoIsBusyAsync2<int>(MethodNameWhichReturnAnInt)
希望它有所帮助!
Hope it helps!
这篇关于如何通用这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!