C#索引器-示例代码

本文介绍了一个C#中的相册类实现案例,通过使用索引器来简化照片的检索过程。具体包括如何利用索引器实现通过整数索引和字符串标题两种方式查找照片。

using System;

public class Photo //这个类是一个相片类
{
private string _title; //相片标题
//先定义默认构造函数
public Photo()
{
//初始化相片标题的构造方法
_title = "我是张三";
}
public Photo(string title)
{
//初始化相片标题的构造方法
_title = title;
}
public string Title
{
//属性
get
{
return _title;
}
}
}

public class Album
{
//相册类
Photo[]photos; //用于存放照片的数组
public Album()
{
//初始化相册大小
photos = new Photo[3];
}
public Album(int capacity)
{
//初始化相册大小
photos = new Photo[capacity];
}
//下面定义索引用于检索照片信息,带有int参数的Photo索引器
public Photo this[int index]
{
get //get方法用于根据索引从索引器中获取照片
{
if (index < 0 || index >= photos.Length)
//有效的索引
{
Console.WriteLine("索引无效");
return null;
}
else
{
return photos[index];
}
}
set
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return ; //set 无返回 所以 return 就可以了。因为这里定义的是Photo类型,不是void类型。必写返回
}
else
{
photos[index] = value;
}
}
}
//根据标题检索照片,但不能根据标题赋值,设置为只读索引。带有string参数的Photo索引器。
public Photo this[string title]
{
get
{
//遍历数组中所有照片
foreach (Photo p in photos)
{
if (p.Title == title)
//判断
return p;
}
Console.WriteLine("没有该照片");
return null;
//使用null指示失败
}
}
}

class Test
{
static void Main(string[]arsg)
{
Album friends = new Album(3); //创建相册大小为3
//创建3张照片
Photo first = new Photo("逍遥");
Photo second = new Photo("太子");
Photo third = new Photo("姚佳");
friends[0] = first;
friends[1] = second;
friends[2] = third;
//按照索引进行查询
Photo objPhoto = friends[2];
Console.WriteLine(objPhoto.Title);
//按名称进行检查
Photo obj2Photo = friends["太子"];
Console.WriteLine(obj2Photo.Title);
}
}

定义索引器的时候使用this关键字,get和set访问器和属性的访问器相同,索引器和数组的属性有点相似,只是数组只通过索引检索,而索引器可以通过重载,自定义访问方式。

注意:将数组作为对象对待更加直观时,才使用索引器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值