PHP有一种语言结构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.
}
}
set
访问器需要是公共的(或者在你初始化它的地方可访问),才能使用对象初始化语法。如果你希望该属性在构造后只读,那么就没有办法了。 - mqp