using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Book
{
private string bid;
private string bname;
public string Bid
{
get { return bid; }
set { bid = value; }
}
public string Bname
{
get { return bname; }
set { bname = value; }
}
}
class Library
{
Book[] book;
public Library(int len)
{
book = new Book[len];
}
public Book this[int idx]
{
get
{
return book[idx];
}
set
{
book[idx] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
int length;
Console.Write("圖書館容量:");
length = Convert.ToInt32(Console.ReadLine());
Library lib = new Library(length);
for (int i = 0; i < length; i++)
{
Book b = new Book();
Console.Write("編號{0}:", i + 1);
b.Bid = Console.ReadLine();
Console.Write("書名{0}:", i + 1);
b.Bname = Console.ReadLine();
lib[i] = b;
}
for (int i = 0; i < 3; i++)
{
Console.WriteLine(lib[i].Bid + " " + lib[i].Bname);
}
}
}
}
這個程序應該是一個習作,目的是練習使用C#的索引器(Indexer)語法。
lib[i] = b;的作用是調用Library定義的那個索引器的set方法,把Book對象b傳給Book[]數組。