using System;
namespace CSharpBook.Chapter07
{
class DayCollection
{ // 星期(字符串)数组
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
}
class Program
{
static void Main(string[] args)
{
DayCollection week = new DayCollection();
Console.WriteLine("{0}:{1}", "Friday", week["Fri"]);
Console.WriteLine("{0}:{1}", "Unknown", week["Unknown"]);
Console.ReadLine();
}
}
}
在其中只需添加代码(不允许改现有的代码)是程序输出
Friday:5
Unknown:-1
---------------------
using System;
namespace CSharpBook.Chapter07
{
class DayCollection
{ // 星期(字符串)数组
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
public int this[string index]
{
get {
for (int i = 0; i < days.Length; i++)
{
if (days[i].ToLower() == index.ToLower())
{
return i;
}
}
return -1;
}
}
}
class Program
{
static void Main(string[] args)
{
DayCollection week = new DayCollection();
Console.WriteLine("{0}:{1}", "Friday", week["Fri"]);
Console.WriteLine("{0}:{1}", "Unknown", week["Unknown"]);
Console.ReadLine();
}
}
}
C#索引器week例子
最新推荐文章于 2022-11-21 09:15:43 发布