2010-08-01 71 views
0
public class Temp 
{ 
    List<T> values = new List<T>; 

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

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

另外請解釋我什麼時候會創建List對象並創建它的類型。告訴我在下列情況下的執行流程

}

回答

0

將首先調用靜態ctor。
然後值列表將是秒和ctor。
閱讀關於beforefieldinit here

+0

ex。如果我創建一個Temp類的對象爲 Temp obj = new Temp(); 列表對象將包含什麼。 因爲它是通用的,它會包含空值嗎? 請建議 – 2010-08-01 20:26:03

+0

它不會包含任何值。檢查Count屬性。另請閱讀本文檔以瞭解鏈接列表是什麼:http://cslibrary.stanford.edu/103/LinkedListBasics.pdf 如果沒有值,List對象本身不爲null。 它只是指向null。 – 2010-08-01 20:48:38

1

看起來該字段先被初始化,然後調用靜態構造函數,然後調用構造函數。

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:

靜態字段初始
靜態構造函數
字段初始
一般構造

[編輯]

哎呀對不起,這是一個非靜態字段我沒有注意到它。

相關問題