0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

カプセル化について

Posted at

カプセル化って??

オブジェクト指向プログラミングにおいて、データやメソッドを閉じ込め、
外部からのアクセスを制限すること

自分のクラスでのみ、編集を可能にする

プロパティでの制御

C#にはオブジェクトの状態を取得・設定するためのアクセサメソッドである
プロパティが存在します。
プロパティ内で値のチェックなど処理を行う
プロパティ:フィールドにアクセスする専用のメソッド

sample.cs
public class Person
{
    private string _name;//これは変数
    
    public string Name //Nameプロパティ ここで値の処理
    {
        get { return _name; }
        set { _name = value; }
    }
}

※変数前に_(アンダーバー)をつけることで、クラス内部で使用される変数を
 示しています

getterとsetter

getでprivateな変数の値を取得(参照)する
setでprivateな変数の値を変更する

privateな変数は外から書き換えなどが不可能なため、getter,setterを用いて
参照、変更を行う

sample2.cs
public class Person
{
  private string _name;//これは変数
  
  public string Name //Nameプロパティ ここで値の処理
  {
      get { return _name; } //_nameを取得
      set { _name = value; }//_nameに値を入れ込む 何もしないままだとvalueに値が自動的に入る
  }
}

また上記の処理は省略が可能(こんな省略しちゃうの..?)
変数の宣言とプロパティを一緒にしてる
※中で処理が必要ないときに有効

sample3.cs
public class Person
{
  public string Name {get;set;}//続けて=takashiと記載すると初期値を設定できる
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?