class Photo
{
string _title;
public Photo(string title)//构造方式,并初始化照片名
{
this._title = title;
}
public string Title//照片名的属性
{
get
{
return _title;
}
}
} class Album
{
Photo[] photos;
public Album(int capacity)//构造方式,并指定相册的大小
{
photos=new Photo[capacity];
}
public Photo this[int index]
{
get
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return null;
}
return photos[index];
}
set
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return;
}
photos[index] = value;
}
}
public Photo this[string title]
{
get
{
foreach (Photo p in photos)//遍历数组中的所有照片
{
if (p.Title == title)
{
return p;
}
}
Console.WriteLine("未找到");
return null;
}
}
} class TestIndexr
{
static void main(string[] args)
{
Album friends = new Album(3); Photo first = new Photo("Jenn");
Photo second = new Photo("Smith");
Photo third = new Photo("Mark");
friends[0] = first;
friends[1] = second;
friends[2] = third; Photo obj1Photo = friends[2];
Console.WriteLine(obj1Photo.Title); Photo obj2Photo = friends["Jenn"];
Console.WriteLine(obj2Photo.Title); }
}
{
string _title;
public Photo(string title)//构造方式,并初始化照片名
{
this._title = title;
}
public string Title//照片名的属性
{
get
{
return _title;
}
}
} class Album
{
Photo[] photos;
public Album(int capacity)//构造方式,并指定相册的大小
{
photos=new Photo[capacity];
}
public Photo this[int index]
{
get
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return null;
}
return photos[index];
}
set
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return;
}
photos[index] = value;
}
}
public Photo this[string title]
{
get
{
foreach (Photo p in photos)//遍历数组中的所有照片
{
if (p.Title == title)
{
return p;
}
}
Console.WriteLine("未找到");
return null;
}
}
} class TestIndexr
{
static void main(string[] args)
{
Album friends = new Album(3); Photo first = new Photo("Jenn");
Photo second = new Photo("Smith");
Photo third = new Photo("Mark");
friends[0] = first;
friends[1] = second;
friends[2] = third; Photo obj1Photo = friends[2];
Console.WriteLine(obj1Photo.Title); Photo obj2Photo = friends["Jenn"];
Console.WriteLine(obj2Photo.Title); }
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货