Understanding C# field initialization requirements

前端 未结 4 1909
一生所求
一生所求 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:55

    The answer is more or less, the designers of C# preferred it that way.

    Since all field initializers are translated into instructions in the constructor(s) which go before any other statements in the constructor, there is no technical reason why this should not be possible. So it is a design choice.

    The good thing about a constructor is that it makes it clear in what order the assignments are done.

    Note that with static members, the C# designers chose differently. For example:

    static int a = 10;
    static int b = a;
    

    is allowed, and different from this (also allowed):

    static int b = a;
    static int a = 10;
    

    which can be confusing.

    If you make:

    partial class C
    {
        static int b = a;
    }
    

    and elsewhere (in other file):

    partial class C
    {
        static int a = 10;
    }
    

    I do not even think it is well-defined what will happen.

    Of course for your particular example with delegates in an instance field initializer:

    Action progress = OnProgress; // ILLEGAL (non-static method OnProgress)
    

    there is really no problem since it is not a read or an invocation of the non-static member. Rather the method info is used, and it does not depend on any initialization. But according to the C# Language Specification it is still a compile-time error.

提交回复
热议问题