DoStuffOnlyOnceAsync我必须尝试调用 using的非静态方法AsyncLazy,但出现错误。如何调用非静态方法?字段初始值设定项不能引用非静态字段、方法或属性“TestClass.DoStuffOnlyOnceAsync()” using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace Registry{public class AsyncLazy<T> : Lazy<Task<T>>{ public AsyncLazy(Func<T> valueFactory) : base(() => Task.Run(valueFactory)) { } public AsyncLazy(Func<Task<T>> taskFactory) : base(() => Task.Run(() => taskFactory())) { } public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }}public class TestClass{ private AsyncLazy<bool> asyncLazy = new AsyncLazy<bool>(async () => { await DoStuffOnlyOnceAsync(); return true; }); public TestClass() { } public async Task DoStuffOnlyOnceAsync() { await Task.FromResult(false); }}}
1 回答
SMILET
TA贡献1796条经验 获得超4个赞
限制是字段初始值设定项不能调用任何非静态方法。AsyncLazy<T>对于任何字段初始值设定项都是如此,与or无关async。
要修复它,请在构造函数中初始化该字段:
public TestClass()
{
asyncLazy = new AsyncLazy<bool>(async () =>
{
await DoStuffOnlyOnceAsync();
return true;
});
}
- 1 回答
- 0 关注
- 93 浏览
添加回答
举报
0/150
提交
取消