开发者

Tell me the flow of execution in the following scenario

public class Temp
{
   List<T> values = new List<T>;

   static Temp()
   {
      System.Cons开发者_C百科ole.WriteLine("static constructor");
   }

   public Temp()
   {
      System.Console.WriteLine("general constructor");
   }
}

Also please explain me when will the List object will be created and with what type it is created.

}


It appears the field gets initialized first, then the static constructor is called, then the constructor.

class Test
{
    string variable = new Func<string>(() =>
    {
        Console.WriteLine("field initializer");
        return "VARIABLE";
    })();

    static string staticvariable = new Func<string>(() =>
    {
        Console.WriteLine("static field initializer");
        return "STATICVARIABLE";
    })();

    static Test()
    {
        System.Console.WriteLine("static constructor");
    }

    public Test()
    {
        System.Console.WriteLine("general constructor");
    }
}

Test t = new Test();

outuput:

static field initializer
static constructor
field initializer
general constructor

[edit]

Oops sorry, it was a non-static field and I didn't notice it.


The static ctor will be called first.
Then values list will be second and the the ctor.
Read about beforefieldinit here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜