简体   繁体   中英

Convert Task<T> to Task<U> where U == typeof a property of T

Given:

An object PolicyResult with a property bool Success {get;}

An instace of 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,

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM