C#中如何让Func可以await

下面的 C# 代码

public async Task<T> GetValueOrCreateAsync<T>(string key, Func<T> factory)
{    //..
    var value = await factory();
}

编译时会报错

CS1061 'Func<T>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Func<T>' could be found (are you missing a using directive or an assembly reference?)


三国纷争
浏览 754回答 1
1回答

慕哥9229398

&nbsp;public&nbsp;async&nbsp;Task<T>&nbsp;GetValueOrCreateAsync<T>(string&nbsp;key,&nbsp;Func<Task<T>>&nbsp;factory) &nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//.. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;value&nbsp;=&nbsp;await&nbsp;factory();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;default(T); }Func<T> - > Func<Task<T>>
打开App,查看更多内容
随时随地看视频慕课网APP