Is there a language construct similar to a PHP () list in C #?

PHP has a language construct list()that provides the assignment of several variables in a single expression.

$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 that can help 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.
    }
}
+3
source share
4 answers

No, I'm afraid there is no good way to do this, and code like your example is often written. This sucks. My condolences.

, :

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

, .

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

" " " "?

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

:

 int a=2, b=3;

. , , :

 a=2; b=3;
+1

Source: https://habr.com/ru/post/1762329/


All Articles