I've been trying to find out the name for something, but without knowning the name, I am having a hard time Googling for the answer. It's a bit of a catch 22. I was hoping that if I posted an example, someone out开发者_如何学JAVA there might recognize it.
Basically, it's a way to initialize any number of public properties of an object, without using a constructor.
For example, if I wanted to dynamically add a text box to my winform, I could:
System.Windows.Forms.TextBox tb_FirstName = new System.Windows.Forms.TextBox()
{
Location = new System.Drawing.Point(0, 0),
Name = "tb_FirstName",
Size = new System.Drawing.Size(100, 20),
TabIndex = 1
};
frm_MyForm.Controls.Add(tb_FirstName);
Does anyone know what this is called? Furthermore, is there a reason why I should avoid doing this. I prefer how the above code reads, as opposed to individually setting properties as such:
System.Windows.Forms.TextBox tb_FirstName = new System.Windows.Forms.TextBox();
tb_FirstName.Location = new System.Drawing.Point(0, 0);
tb_FirstName.Name = "tb_FirstName";
tb_FirstName.Size = new System.Drawing.Size(100, 20);
tb_FirstName.TabIndex = 1;
frm_MyForm.Controls.Add(tb_FirstName);
Mostly, I jsut want to know the name of the first example, so that I can do a little reading on it.
It's called an object initializer.
One potential issue with their use is when using an object initializer for an object in a using statement. If any of the property setters throws an exception, or evaluating code for the value of the property does, dispose will never be called on the object.
For example:
using (Bling bling = new Bling{ThrowsException = "ooops"})
{
//Some code...
}
An instance of Bling
will be created, but because property ThrowsException
throws an exception, Dispose
will never be called.
As @chibacity says, it's an object initializer. Keep in mind that using an initializer does not bypass the constructor. A constructor must still be invoked.
By the way, the ()
isn't necessary if you're using the default constructor for your initializer. This also works:
var tb_FirstName = new TextBox {
Location = new System.Drawing.Point(0, 0),
Name = "tb_FirstName",
Size = new System.Drawing.Size(100, 20),
TabIndex = 1
};
精彩评论