是否有类似于 C# 中 PHP 的 list() 的语言构造?
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.
}
}
PHP has a language construct list()
which provides multiple variables assignment in one statement.
$a = 0;
$b = 0;
list($a, $b) = array(2, 3);
// Now $a is equal to 2 and $b is equal to 3.
Is there a similar thing in C#?
If not, is there any workaround which may help to avoid code like the following, without having to deal with reflection?
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.
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,恐怕没有任何好的方法可以做到这一点,并且像您的示例这样的代码经常被编写。太糟糕了。我的哀悼。
如果您愿意为了简洁而牺牲封装,则可以在这种情况下使用对象初始值设定项语法而不是构造函数:
No, I'm afraid there isn't any good way to do that, and code like your example gets written often. It sucks. My condolences.
If you're willing to sacrifice encapsulation for concision, you can use object initializer syntax instead of a constructor for this case:
我认为您正在寻找对象和集合初始值设定项。
例如,名字和姓氏都是 Person 类的属性。
I think you're looking for object and collection initializers.
for example where Firstname and Lastname are both properties of the class Person.
“多变量初始化”或“多变量赋值”?
对于初始化
将是:
对于分配,没有捷径。它必须是两个语句,但如果您愿意,可以将这两个语句放在一行上:
"Multiple variable initialization" or "Multiple variable assignment" ?
For initialization
would be:
For assignment, there's no shortcut. It has to be two statement, but if you like, you can put the two statements on one line:
是的 - 您可以使用对象初始值设定项消除构造函数中的所有代码(C# 3.0 的新增功能)。这是一个很好的解释:
http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx
Yes - you can eliminate all the code in the constructor with object initializers (new for C# 3.0). Here is a pretty good explanation:
http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx