开发者

.NET - define a new control instance's properties in short way?

开发者 https://www.devze.com 2023-02-03 23:03 出处:网络
In general, if we have to create new control instance, we will do the following: Literal ltl= new Literal();

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"});
0

精彩评论

暂无评论...
验证码 换一张
取 消