2010-08-30 45 views
3

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

回答

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, 
    // ... 
}; 
+0

打我吧。 +1 – 2010-08-30 18:21:24

+0

如果使用自动属性(C#3.0及更高版本,以及对象初始值设定项),则无需牺牲封装:http://msdn.microsoft.com/zh-cn/library/bb384054.aspx – 2010-08-30 18:28:18

+2

仍然存在牺牲;为了使用对象初始化语法,属性上的'set'访问器需要是公开的(或者在你初始化它的任何地方都可以访问)。如果您希望在施工后将该物业设为只读,那么您的运气不佳。 – mquander 2010-08-30 18:36:10

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;} 
} 
+0

这里是C#编程指南链接:http://msdn.microsoft.com/en-us/library/bb384062.aspx – 2010-08-30 18:29:42

+0

不,我在我的情况下不能使用它,因为已经有属性,包含执行一些有效性检查和操作的setter。但是这可以在'Vehicle'代码示例中使用。 – 2010-08-30 18:39:10

1

“多变量初始化” 或 “多变量赋值”?

有关初始化

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

是:

int a=2, b=3; 

对于分配,有没有捷径。它是两个说法,但如果你喜欢,你可以把两个语句在一行:

a=2; b=3; 
+0

在我的问题中出现错误。我正在谈论多变量*赋值*。感谢注意它。 – 2010-08-30 18:35:49

相关问题