Ars*_*nko 3 php c# language-construct syntactic-sugar c#-4.0
PHP有一个语言结构list()
,它在一个语句中提供多个变量赋值.
$a = 0;
$b = 0;
list($a, $b) = array(2, 3);
// Now $a is equal to 2 and $b is equal to 3.
Run Code Online (Sandbox Code Playgroud)
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.
}
}
Run Code Online (Sandbox Code Playgroud)
不,我担心没有任何好的方法可以做到这一点,像你的例子这样的代码经常被写入.太糟糕了.节哀顺变.
如果您愿意为了简洁而牺牲封装,那么在这种情况下您可以使用对象初始化器语法而不是构造函数:
public class Vehicle
{
public string modelName;
public int maximumSpeed;
public int weight;
public bool isDiesel;
// ... Dozens of other fields.
}
var v = new Vehicle {
modelName = "foo",
maximumSpeed = 5,
// ...
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
151 次 |
最近记录: |