前記事(C#:プロパティを理解する)で書いたように、C#には、プロパティと呼ばれるメソッドと変数の中間のものがあります。
int型のプロパティは、通常のint型変数のようにインクリメント演算が使えます。また、set時に値の上限下限の制限を与えることで、予期せぬ値の変更に対応することができます。
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 Program { | |
static void Main(string[] args) { | |
testData td = new testData(); | |
for (int i = 0; i < 20; i++) { | |
td.Count++; | |
Console.WriteLine(td.Count); | |
} | |
Console.ReadKey(); | |
} | |
} | |
class testData { | |
private int max = 10; | |
private int count; | |
public int Count { | |
get { return count; } | |
set { | |
if (value <= max) { | |
count = value; | |
} | |
} | |
} | |
} |
0 件のコメント:
コメントを投稿