簡體   English   中英

此構造函數語法的名稱是什么?

[英]What is the name of this constructor syntax?

我習慣這種語法:

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
                           };

這應該與上面的示例相同,但是將調用哪個Constructor,然后程序如何進行? 此語法是否有特殊名稱? 我必須在自己的類中添加什么才能能夠像這樣構造它們?

那等於您的第二個代碼。 編譯器會將其轉換為:

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

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

在這種情況下,您還需要一個無參數的構造函數,因為:

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

等價於:

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

因此,您正在調用無參數構造函數。 您還可以將對象初始化器與其他構造函數一起使用,如注釋中所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM