PHP的语言结构为list()
,它在一个语句中提供多个变量赋值。在C#中是否有与PHPs list()类似的语言结构?
$a = 0;
$b = 0;
list($a, $b) = array(2, 3);
// Now $a is equal to 2 and $b is equal to 3.
C#中是否有类似的东西?
如果没有,是否有任何解决方法可能有助于避免类似以下的代码,而不必处理反射?
public class Vehicle
{
private string modelName;
private int maximumSpeed;
private int weight;
private bool isDiesel;
// ... Dozens of other fields.
public Vehicle()
{
}
public Vehicle(
string modelName,
int maximumSpeed,
int weight,
bool isDiesel
// ... Dozens of other arguments, one argument per field.
)
{
// Follows the part of the code I want to make shorter.
this.modelName = modelName;
this.maximumSpeed = maximumSpeed;
this.weight= weight;
this.isDiesel= isDiesel;
/// etc.
}
}
打我吧。 +1 – 2010-08-30 18:21:24
如果使用自动属性(C#3.0及更高版本,以及对象初始值设定项),则无需牺牲封装:http://msdn.microsoft.com/zh-cn/library/bb384054.aspx – 2010-08-30 18:28:18
仍然存在牺牲;为了使用对象初始化语法,属性上的'set'访问器需要是公开的(或者在你初始化它的任何地方都可以访问)。如果您希望在施工后将该物业设为只读,那么您的运气不佳。 – mquander 2010-08-30 18:36:10