Understanding C# field initialization requirements

前端 未结 4 1901
一生所求
一生所求 2020-12-06 09:15

Considering the following code:

public class Progressor
{
    private IProgress progress = new Progress(OnProgress);

    private void          


        
4条回答
  •  天命终不由人
    2020-12-06 09:35

    Section 10.5.5.2: Instance field initialization describes this behavior:

    A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name

    This behavior applies to your code because OnProgress is an implicit reference to the instance being created.

提交回复
热议问题