Compiler Error CS8177
Async methods cannot have by-reference locals
To manage asynchronous state, async
methods use a state machine, capturing variable state in closures implemented in compiler-generated classes and properties. A local variable reference (on the stack) can't be captured within the instance of a class in the heap, so the compiler issues an error.
Example
The following sample generates CS8177 before C# 13:
// CS8177.cs (20,26)
using System.Threading.Tasks;
class E
{
public class Enumerator
{
public ref int Current => throw new System.NotImplementedException();
public bool MoveNext() => throw new System.NotImplementedException();
}
public Enumerator GetEnumerator() => new Enumerator();
}
class C
{
public async static Task Test()
{
await Task.CompletedTask;
foreach (ref int x in new E())
{
System.Console.Write(x);
}
}
}
To correct this error
Remove the ref
modifier. Or, you can upgrade to C# 13, which ships with .NET 9.
class C
{
public async static Task Test()
{
await Task.CompletedTask;
foreach (int x in new E())
{
System.Console.Write(x);
}
}
}
Tee yhteistyötä kanssamme GitHubissa
Tämän sisällön lähde on GitHubissa, jossa voit myös luoda ja tarkastella ongelmia ja pull-pyyntöjä. Katso lisätietoja osallistujan oppaasta.