如何解决为什么返回 IAsyncEnumerable 的异步方法作为类而不是结构实现?
我很好奇为什么异步方法返回 IAsyncEnumerable
编译到状态机,状态机被定义为类而不是通常的结构。请参见以下示例:
public async IAsyncEnumerable<int> MethodOne()
{
await Task.Delay(10);
yield return 0;
}
// Compiled version
[CompilerGenerated]
private sealed class <MethodOne>d__0 : IAsyncEnumerable<int>,IAsyncEnumerator<int>,IAsyncDisposable,IValueTaskSource<bool>,IValueTaskSource,IAsyncStateMachine
{
// Omitted for brevity
}
public async Task<int> MethodTwo()
{
await Task.Delay(10);
return 0;
}
// Compiled version
[StructLayout(LayoutKind.Auto)]
[CompilerGenerated]
private struct <MethodTwo>d__0 : IAsyncStateMachine
{
// Omitted for brevity
}
解决方法
状态机本身实现IAsyncEnumerable<T>
,并new
设置并作为IAsyncEnumerable<T>
实例返回。如果它是一个结构类型,无论如何它都会立即被转换为接口类型。
您可以将其与为 IEnumerable<T>
生成的状态机进行比较,public IEnumerable<int> MethodThree()
{
yield return 0;
}
// Compiled version
[CompilerGenerated]
private sealed class <MethodThree>d__0 : IEnumerable<int>,IEnumerable,IEnumerator<int>,IDisposable,IEnumerator
{
// Omitted for brevity
}
[IteratorStateMachine(typeof(<MethodThree>d__0))]
public IEnumerable<int> MethodThree()
{
return new <MethodThree>d__0(-2);
}
也是一个类:
{{1}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。