using System;
struct Member
{
public string name;
public int age;
public string seibetsu;
public Member
(string n, int a, string s)
{
name = n;
age = a;
seibetsu = s;
}
}
class Family
{
int ninzu;
// Length5のMember型の配列を定義
Member[] member = new Member[5];
public bool addMember(Member n)
{
if (ninzu < member.Length)
{
member[ninzu++] = n;
return true;
}
return false;
}
// 配列の要素を出力
public void printMember()
{
foreach (Member m in member)
{
if(m.name !=null)
{
Console.WriteLine
("{0} {1} {2}",
m.name, m.age, m.seibetsu);
}
}
}
// 構造体の戻り値を設定
public Member getMember(int i)
{
try
{
return member[i];
}
catch (Exception)
{
return new Member();
}
}
}
class MainClass
{
static void Main()
{
// 構造体のインスタンス化
Family f = new Family();
string s1 = "Man",
s2 = "Woman";
// Member型の値を定義
Member f1 = new Member
("Kamimura1", 0, s1);
Member f2 = new Member
("Kamimura2", 10, s2);
Member f3 = new Member
("Kamimura3", 20, s1);
Member f4 = new Member
("Kamimura4", 30, s2);
Member f5 = new Member
("Kamimura5", 40, s1);
Member f6 = new Member
("Kamimura6", 50, s2);
Member f7 = new Member
("Kamimura7", 60, s1);
Member f8 = new Member
("Kamimura8", 70, s2);
Member f9 = new Member
("Kamimura9", 80, s1);
Member f10 = new Member
("Kamimura10", 90, s2);
// Member型の値を追加
f.addMember(f1);
f.addMember(f2);
f.addMember(f3);
f.addMember(f4);
f.addMember(f5);
// コンストラクタの呼び出し
f.printMember();
// インデックスの範囲を超えてみる
/* インデックス5以上は int型の既定値の
* 0だけが出力される
* 出力値:,0, */
int i = 0;
while(i<10)
{
Member m=f.getMember(i++);
Console.WriteLine
("{0},{1},{2}",
m.name, m.age, m.seibetsu);
}
}
}
0 コメント:
コメントを投稿