3

PHP には、list()1 つのステートメントで複数の変数の割り当てを提供する言語構造があります。

$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;

割り当てには、ショートカットはありません。2つのステートメントである必要がありますが、必要に応じて、2つのステートメントを1行に配置できます。

 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 に答える