ブラケットを用いてクラスに配列表現を加えるインデクサを学ぼう。
●Colors.cs
using System;
using System.Collections.Generic;
namespace IndexerLesson
{
public class Colors
{
private string[] data = { "赤", "青", "黄" };
//アクセス 戻り値 this[型 引数]
public string this[int index]{
set{
this.data[index] = value;
}
get{
return data[index];
}
}
}
}
●Program.cs
using System;
namespace IndexerLesson
{
class Program
{
static void Main(string[] args)
{
Colors colors = new Colors();
for (int i = 0; i < 3;i++){
Console.WriteLine(colors[i]);
}
colors[0] = "黒";
Console.WriteLine(colors[0]);
}
}
}
オーバーロード可能
●JMonth.cs
using System;
using System.Collections.Generic;
namespace IndexerLesson
{
public class JMonth
{
private string[] months = { "睦月", "如月", "弥生", "卯月", "皐月", "水無月", "文月", "葉月", "長月", "神無月", "霜月", "師走" };
public string this[int index]{
get{
return months[index - 1];
}
}
public int this[string name]{
get{
return Array.IndexOf(months, name) + 1;
}
}
}
}
●Program.cs
using System;
using System.Collections.Generic;
namespace IndexerLesson
{
class Program
{
static void Main(string[] args)
{
JMonth jMonth = new JMonth();
Console.WriteLine(jMonth[6]);
Console.WriteLine(jMonth["神無月"]);
}
}
}
問
インデクサを用いたクラスを作成し、県コードを調べる処理を作成せよ。
[実行例]
1...県コード->県,2...県->県コード>1 県コードを入力>13 東京都 1...県コード->県,2...県->県コード>2 県名を入力>広島県 34 1...県コード->県,2...県->県コード>3 終了
[解答例]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IndexerLesson3 {
class Program {
static void Main(string[] args) {
Pref pref = new Pref();
while (true) {
Console.Write("1...県コード->県,2...県->県コード>");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
Console.Write("県コードを入力>");
int code = int.Parse(Console.ReadLine());
Console.WriteLine(pref[code]);
}else if(input == 2) {
Console.Write("県名を入力>");
string name = Console.ReadLine();
Console.WriteLine(pref[name]);
} else {
Console.WriteLine("終了");
break;
}
}
}
}
class Pref {
string[] data=
{"北海道","青森県","岩手県","宮城県","秋田県",
"山形県","福島県","茨城県","栃木県","群馬県",
"埼玉県","千葉県","東京都","神奈川県","新潟県",
"富山県","石川県","福井県","山梨県","長野県",
"岐阜県","静岡県","愛知県","三重県","滋賀県",
"京都府","大阪府","兵庫県","奈良県","和歌山県",
"鳥取県","島根県","岡山県","広島県","山口県",
"徳島県","香川県","愛媛県","高知県","福岡県",
"佐賀県","長崎県","熊本県","大分県","宮崎県",
"鹿児島県","沖縄県"};
public string this[int index] {
get {
return data[index - 1];
}
}
public int this[string pref] {
get {
return Array.IndexOf(data, pref) + 1;
}
}
}
}

コメント