web-dev-qa-db-ja.com

C#6.0の読み取り専用プロパティ

Microsoftは、以下のようにプロパティを読み取り専用に設定できる新しい構文をC#6に導入しました。

public class Animal
{
    public string MostDangerous { get; } = "Mosquito";
}

そのようなアプローチの付加価値は何かと思います。

書くだけの違いは何ですか:

public class Animal
{
    public const string MostDangerous = "Mosquito";
}

あるいは:

public class Animal
{
    public string MostDangerous 
    { 
        get
        {
            return "Mosquito";
        }
    }
}
12
ehh

あなたの例は、すべての可能性を示すことができない文字列定数を使用しています。このスニペットを見てください:

class Foo
{
    public DateTime Created { get; } = DateTime.Now;  // construction timestamp

    public int X { get; } 

    public Foo(int n)
    {
        X = n;  // writeable in constructor only
    }
}

読み取り専用プロパティはインスタンスごとであり、コンストラクターから設定できます。コンパイル時に値を決定する必要があるconstフィールドとは大きく異なります。プロパティ初期化子は別個の機能であり、フィールド初期化子の規則と制限に従います。

19
Henk Holterman

新しい構文は、C#の冗長性を減らすための取り組みです。それは単なる構文糖衣です。生成されるILは、ゲッターとバッキングストアを備えた自動プロパティに似ています。

2
Sameer Khan

このC#の改善は、VBから直接行われたものであり、バッキングフィールドとコンストラクター初期化子を実装する必要がありません。

Public ReadOnly dateStamp As DateTime = Datetime.Now
1