这个构造函数语法的名称是什么?

Ale*_*der 1 c# constructor

我习惯了这种语法:

DirectorySearcher ds = new DirectorySearcher(forestEntry,filter);
Run Code Online (Sandbox Code Playgroud)

这个语法:

DirectorySearcher ds = new DirectorySearcher();
ds.SearchRoot = forestEntry;
ds.Filter = filter;
Run Code Online (Sandbox Code Playgroud)

他们都只使用不同的构造函数,没有.1只能工作,因为存在2参数构造函数,而不存在.2仅适用,因为SearchRoot和Filter在构造后不是只读的.

现在我得到了这种语法的代码:

DirectorySearcher ds = new DirectorySearcher
                           {
                               SearchRoot = forestEntry,
                               Filter = filter
                           };
Run Code Online (Sandbox Code Playgroud)

这应该与上面的示例相同,但调用哪个Constructor以及程序如何继续?这种语法有特殊名称吗?我必须添加到我自己的类中才能像这样构建它们?

Sel*_*enç 10

这是你的第二个代码的等价物.编译器会将其转换为:

DirectorySearcher ds = new DirectorySearcher();
ds.SearchRoot = forestEntry;
ds.Filter = filter;
Run Code Online (Sandbox Code Playgroud)

这称为对象inializers.您可以将对象初始值设定项语法与类的公共属性和字段一起使用.唯一的例外是readonly字段.由于它们只能在构造函数中初始化,因此无法在初始化程序中使用它们.

在这种情况下,您还需要一个无参数构造函数,因为:

DirectorySearcher ds = new DirectorySearcher
                       {
                           SearchRoot = forestEntry,
                           Filter = filter
                       };
Run Code Online (Sandbox Code Playgroud)

是平等的:

DirectorySearcher ds = new DirectorySearcher() // note the parentheses
                       {
                           SearchRoot = forestEntry,
                           Filter = filter
                       };
Run Code Online (Sandbox Code Playgroud)

所以你要调用无参数构造函数.您还可以将注释器与其他构造函数一起使用,如注释中所述.

  • @ Selman22:不,不是必需的; 一个构造函数调用,如`MyClass c = new MyClass("Some string"){OtherProperty ="Another string"};`完全有效,如果存在相应的构造函数和属性. (5认同)
  • "公共无参数构造函数"不是*使用对象初始值设定项的要求. (3认同)