2014-12-02 45 views
1

我用這個語法:這個構造函數的語法是什麼?

DirectorySearcher ds = new DirectorySearcher(forestEntry,filter); 

和語法如下:

DirectorySearcher ds = new DirectorySearcher(); 
ds.SearchRoot = forestEntry; 
ds.Filter = filter; 

他們都只是用不同的構造,沒有。 1只有2個參數的構造函數存在,並且沒有。 2僅適用,因爲SearchRoot和Filter在構建後不是隻讀的。

現在我得到了代碼的語法如下:

DirectorySearcher ds = new DirectorySearcher 
          { 
           SearchRoot = forestEntry, 
           Filter = filter 
          }; 

這也應該這樣做上面的例子,但構造函數被調用,程序如何然後繼續?這個語法有一個特殊的名字嗎?爲了能夠像這樣構建它們,我需要添加什麼?

+10

[** Object Initializer **](http://msdn.microsoft.com/zh-cn/library/bb384062.aspx) – 2014-12-02 13:18:47

+2

爲什麼不學習C#的基本語法?這是對象初始化語法。很基本。 – TomTom 2014-12-02 13:19:41

+0

從評論和編輯到下面的答案的計數看來,一個完整的答案是相當複雜的,所以真的有必要downvote這個問題,理由是它是「非常基本」...... – Alexander 2014-12-02 13:35:08

回答

10

這就等於你的第二個代碼。編譯器會將其翻譯爲:

DirectorySearcher ds = new DirectorySearcher(); 
ds.SearchRoot = forestEntry; 
ds.Filter = filter; 

這叫做object inializers。您可以使用對象初始值設定項語法與您的類的公共屬性和字段。唯一的例外是readonly字段。由於它們只能在構造函數中初始化,因此不能在初始化程序中使用它們。

在這種情況下,你還需要一個參數的構造函數,因爲這樣的:

DirectorySearcher ds = new DirectorySearcher 
         { 
          SearchRoot = forestEntry, 
          Filter = filter 
         }; 

是equivelant到:

DirectorySearcher ds = new DirectorySearcher() // note the parentheses 
         { 
          SearchRoot = forestEntry, 
          Filter = filter 
         }; 

所以你調用參數的構造函數。您也可以使用註釋中指出的其他構造函數的對象內置函數。

+0

也許這將是值得的談及對只讀字段的影響。 – ken2k 2014-12-02 13:20:34

+3

「公共無參數構造函數」不是使用對象初始值設定項的要求。 – 2014-12-02 13:21:59

+1

@ O.R.Mapper yes是必需的。否則該代碼將無效'DirectorySearcher ds = new DirectorySearcher();'。 – 2014-12-02 13:23:04

相關問題