Constructors versus Initializors in C# [duplicate]
Possible Duplicate:
What's the difference between an object initializer and a construc开发者_高级运维tor?
In c# you can construct an object like:
public class MyObject{
int val1;
int val2;
public MyObject(int val1, val2){
this.val1 = val1;
this.val2 = val2;
}
}
With:
MyObject ob = new MyObject(1,2);
or with:
MyObject ob = new MyObject(){ val1 = 1, val2 = 2 };
What is the diference between that kind of constructors?
MyObject ob = new MyObject(){ val1 = 1, val2 = 2 };
is just syntactic sugar (i.e. shorthand) for
MyObject ob = new MyObject();
ob.val1 = 1;
ob.val2 = 2;
One difference between the two is that you can set readonly fields from the constructor, but not by using the shorthand.
A second difference is that a constructor with parameters forces the client to provide those values. See Constructor-injection vs. Setter injection for a good bit of background reading.
The difference is probably that the second won't compile.
You are missing a default constructor, which it calls in your second example.
MyObject ob = new Object(1,2);
This is constructing the object, and doing something with the values in the constructor. It maybe setting the values, it may not. It depends on the logic in the constructor.
MyObject ob = new Object(){ val1 = 1, val2 = 2 };
This is constructing the object using the default constructor, and setting initial values for properties, after the object has been constructed. In this scenario, setting the values has nothing to do with the constructor besides the fact that it is in the same statement. It's the same as:
MyObject ob = new Object();
ob.val1 = 1;
...
What is neat about this syntax is that you can do:
Object ob = new Object(){ val1 = 1, val2 = 2 };
instead of having to do:
Object ob = new Object(1,2);
((MyObject)ob).val1 = 1; //note having to cast.
...
because the initialization of the variables happens without touching the variable assignment.
The second form
MyObject ob = new Object(){ val1 = 1, val2 = 2 };
is the syntax for
MyObject ob = new Object();
ob.val1 = 1;
ob.val2 = 2;
the key point is that the setting of the values is not part of the constructor.
Both aren't the same thing.
This is invoking class constructor:
MyObject ob = new Object(1,2);
And this is an inline object initializer:
MyObject ob = new Object(){ val1 = 1, val2 = 2 };
First ensures creating an instance of MyObject requires two integer input parameters during construction time, while the other one, just initializes some fields or properties after construction time. Last one keeps freedom of not necessarily initialize such properties and/or fields.
The first is a parameter ctor
MyObject ob = new MyObject (1,2);
The second is the default (zero parameter) ctor, but once the ctor finishes, val1 and val2 are initialized with the values provided
MyObject ob = new MyObject (){ val1 = 1, val2 = 2 };
Also, you can call the second one w/o the braces. E.g.
MyObject ob = new MyObject { val1 = 1, val2 = 2 };
精彩评论