2012-01-10 15 views
0

可能性の重複:私有財産


Differences between Private Fields and Private Properties

だが、私は私有財産を持っているMyPropでMyClassクラスがあるとしましょう。

public class MyClass 
{ 
    private int MyProp { get; set; } 
} 

public class MyClass 
{ 
    private int MyProp = 0; 
} 

使用することをお勧め何の違いは何ですか?おかげさまで

+0

最初のものは、プロパティです。 2番目のフィールドはフィールドです。 – DOK

+1

同じタイプの質問の繰り返し... http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Lloyd

+0

http://stackoverflow.com/questions/653536/difference-between- c-sharp-in-c-sharpフィールド http://csharpindepth.com/articles/chapter8/propertiesmatter.aspx –

答えて

0

通常は、パブリックプロパティとプライベートフィールドの組み合わせを持っている:

public class MyClass 
{ 
    private int _someInt; 

    public int SomeInt { get { return _someInt; } set { _someInt = value; } } 
} 

これは常にあなたは、クラスデータの抽象化層(パブリックプロパティ)(プライベートフィールド)を作成します。ただプロパティを作成すると、プライベートフィールド(私は信じる)が生成されます。プライベートフィールドは必要ですか?いいえ、明示的に宣言することはお勧めです。クラス内でこのようにして、メンバーはプライベートフィールドを利用します。

関連する問題