フィールドとプロパティの違いは何ですか? 質問する

フィールドとプロパティの違いは何ですか? 質問する

C# では、フィールドとプロパティの違いは何ですか? また、プロパティの代わりにフィールドを使用する必要があるのはどのような場合ですか?

ベストアンサー1

プロパティはフィールドを公開します。フィールドは (ほとんどの場合) クラスに対してプライベートに保持され、get プロパティと set プロパティを介してアクセスされます。プロパティは抽象化のレベルを提供し、クラスを使用するものによる外部アクセス方法に影響を与えずにフィールドを変更できるようにします。

public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property. When accessed it uses the underlying field,
    // but only exposes the contract, which will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }

    // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty { get; set; } 
}

@Kent は、プロパティはフィールドをカプセル化する必要はなく、他のフィールドで計算を実行したり、他の目的に使用したりできることを指摘しています。

@GSS は、プロパティにアクセスしたときに検証などの他のロジックも実行できることを指摘しており、これはもう 1 つの便利な機能です。

おすすめ記事