オブジェクト指向言語においては、変数の隠蔽化などはよく利用される手法ですが、一般的には?というかJavaでは、getter/setterメソッドを実装した制御が一般的です。しかしこの方法は、実質メソッドが増えることになり、美しくないです。C#には(マイクロソフト系言語には)、
- プロパティと呼ばれる関数と変数の中間的なもの
が存在します。これは、
- 内部的にはメソッドのように処理が可能
- 外部からは変数のように扱われる
という特徴があります。つまり、外部からは「値を代入」すればいいわけです。積極的に活用しましょう。記述方法は下記のとおりです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Mark{ | |
private int x; | |
private int y; | |
public int X { | |
set { | |
this.x = value; | |
} | |
get { | |
return this.x; | |
} | |
} | |
public int Y { | |
set { | |
this.y = value; | |
} | |
get { | |
return this.y; | |
} | |
} | |
} |
0 件のコメント:
コメントを投稿