简体   繁体   中英

What is the name of this constructor syntax?

I am used to this syntax:

DirectorySearcher ds = new DirectorySearcher(forestEntry,filter);

and to this syntax:

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

They are both just using different Constructors, no. 1 only works because a 2-argument constructor exist, and no. 2 only works because SearchRoot and Filter are not readonly after construction.

Now I was given code with this syntax:

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

This should do the same as the examples above, but which Constructor is called and how does the program proceed then? Does this syntax have a special name? What would I have to add to my own classes to be able to construct them like this?

That is equivelant of your second code. Compiler will translate it into:

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

This is called object inializers . You can use the object initializer syntax with the public properties and fields of your class.The only exception to this is readonly fields. Since they can only be initialized in the constructor you can't use them in an initializer.

In this case you need also a parameterless constructor because this:

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

is equivelant to:

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

So you are calling the parameterless constructor. You can also use object inializers with other constructors as noted in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM