2015-12-04 38 views
1

是使用C#设置块中对象属性的一种方法,类似于您如何编写对象初始值设定项?C#:在一个块中设置对象的属性

例如:

Button x = new Button(){ 
    Text = "Button", 
    BackColor = Color.White 
}; 

是否有与此类似,可以是属性的对象被创建后语法?

例如:

Button x = new Button(); 
x{ 
    Text = "Button", 
    BackColor = Color.White 
}; 
+0

可能的复制[With块等效于C#?(http://stackoverflow.com/questions/481725/with-block-equivalent-in-c) – sstan

+0

这被称为[对象初始化]( https://msdn.microsoft.com/en-us/library/bb384062.aspx),只能在新建对象时使用。你的第二段代码根本无效C#。 –

+0

谢谢 - Pieter Witvoet.You给了我我想要的答案 –

回答

0

这种形式

Button x = new Button(){ 
    Text = "Button", 
    BackColor = Color.White 
}; 

是语法仅构造和构造的一部分。你不能在下一行使用相同的语法。尽管如此,您可以省略(),并将var用于变量类型,从而为您提供更紧凑的结果;

var x = new Button{ 
    Text = "Button", 
    BackColor = Color.White 
}; 

施工后,更新它的唯一方法是通过正常的分配操作;

x.Text = "Button"; 
+0

谢谢。你给了我我想要的答案:“是......的一部分。” –

+0

点击那个灰色的勾号对我来说? :) –

0

可能是你想要吗?

Button x = new Button(); 
x.Text = "Button"; 
x.BackColor = Color.White; 
+0

不,我不想要这个。我知道这是我。我想要这个第二个例子。 –

0

您可以使用属性初始值设定项来执行此操作。

Button x = new Button { Text = "Button", BackColor = Color.White }; 
+1

这与问题中的第一个列表相同。 OP一旦创建实例,就要求能够对实例本身执行此操作。 –

1

你可以不喜欢这样;说你有一个叫Platypus的班级。

你爷爷的方式:

Platypus p = new Platypus(); 
p.CWeek = "1"; 
p.CompanyName = "Pies from Pablo"; 
p.PADescription = "Pennsylvania is the Keystone state (think cops)"; 

新奇的方式:

Platypus p = new Platypus 
{ 
    CWeek = "1", 
    CompanyName = "Pies from Pablo", 
    PADescription = "Pennsylvania is the Keystone state (think cops)" 
}; 
+1

这必须是我见过的最随机的示例代码。有创意的方式 – bit2know

+0

这并没有回答这个问题。在对象已创建后,他要求提供特殊语法来设置属性***。 – sstan

+0

最了解我想表达的人 - 谢谢。我得到了我的答案。没有我想要的方式。 –