3

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.
    }
}
4

4 回答 4

5

不,恐怕没有任何好的方法可以做到这一点,并且像您的示例这样的代码经常被编写。糟透了。节哀顺变。

如果您愿意为了简洁而牺牲封装,则可以在这种情况下使用对象初始值设定项语法而不是构造函数:

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,
    // ...
};
于 2010-08-30T18:19:55.117 回答
2

我认为您正在寻找对象和集合初始值设定项

var person = new Person()
{
    Firstname = "Kris",
    Lastname = "van der Mast"
}

例如,Firstname 和 Lastname 都是 Person 类的属性。

public class Person
{
    public string Firstname {get;set;}
    public string Lastname {get;set;}
}
于 2010-08-30T18:20:48.377 回答
1

“多变量初始化”还是“多变量赋值”?

用于初始化

$a = 0; 
$b = 0; 
list($a, $b) = array(2, 3); 

将会:

 int a=2, b=3;

对于分配,没有捷径可走。它必须是两个语句,但如果您愿意,可以将两个语句放在一行:

 a=2; b=3;
于 2010-08-30T18:20:59.863 回答
0

是的 - 您可以使用对象初始化程序(C# 3.0 的新功能)消除构造函数中的所有代码。这是一个很好的解释:

http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx

于 2010-08-30T18:25:37.740 回答