In general, if we have to create new control instance, we will do the following:
Literal ltl= new Literal();
ltl.ID = "ltlControl1";
ltl.Text = "SomeText";
PlaceHolder.Controls开发者_开发问答.Add(ltl);
But is it possible define the properties like that to shorten the syntax?
Literal ltl= new Literal( ID = "ltlControl1", Text = "SomeText");
Yes, by using the object initializer syntax. You're close; substitute the parentheses with curly braces to assign the properties.
Literal ltl = new Literal { ID = "ltlControl1", Text = "SomeText" };
For more information refer to Object and Collection Initializers.
You can do the following with C# object initializers.
var ltl = new Literal {
ID = "ltlControl1",
Text = "SomeText"
};
Placeholder.Controls.Add(ltl);
Or even shorter if you don't need the ltl
variable.
Placeholder.Controls.Add(new Literal {ID="ltlControl1", Text="SomeText"});
精彩评论