[英]Convert Task<T> to Task<U> where U == typeof a property of T
Given: 鉴于:
An object PolicyResult with a property bool Success {get;}
具有属性bool Success {get;}
的对象PolicyResult
An instace of Task<PolicyResult>
() Task<PolicyResult>
()的Task<PolicyResult>
What I'm currently doing: 我目前正在做什么:
I can get the value of the success property this way: 我可以通过以下方式获取成功属性的值:
PolicyResult result = await myTask;
bool success = result.Success
Now i would like to change the Task<PolicyResult>
to get a Task<bool>
which wraps the origin Task, 现在,我想更改Task<PolicyResult>
以获得一个包装原始Task的Task<bool>
,
For this i have done this code: 为此,我完成了以下代码:
Task<bool> foo = myTask.ContinueWith(i => i.Result.Success);
But that smells for me as it is now obvious that i want only select the specific property. 但这对我来说很香,因为现在很明显我只想选择特定的属性。
Is there a better / more elegant way to do this ? 有没有更好/更优雅的方式来做到这一点? Am I overseeing something ? 我在监督什么吗?
You can create an extension method: 您可以创建扩展方法:
public static async Task<U> Select<T, U>(this Task<T> task, Func<T, U> selector)
{
return selector(await task);
}
Task<bool> foo = myTask.Select(r => r.Success);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.