代码之家  ›  专栏  ›  技术社区  ›  Arseni Mourzenko

是否有类似于c_中phps list()的语言结构?

  •  3
  • Arseni Mourzenko  · 技术社区  · 15 年前

    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 回复  |  直到 15 年前
        1
  •  5
  •   mqp    15 年前

    不,恐怕没有任何好的方法可以做到这一点,像您的示例这样的代码经常被编写。它很烂。我表示哀悼。

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

    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,
        // ...
    };
    
        2
  •  2
  •   Kris van der Mast    15 年前

    我想你在找 对象和集合初始值设定项 .

    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;}
    }
    
        3
  •  1
  •   James Curran    15 年前

    “多变量 初始化 “或”多变量 分配 “?

    用于初始化

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

    将是:

     int a=2, b=3;
    

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

     a=2; b=3;
    
        4
  •  0
  •   Inverseofverse    15 年前

    是-可以使用对象初始值设定项消除构造函数中的所有代码(对于C 3.0是新的)。下面是一个很好的解释:

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