C#索引器封装
Posted FranticPinK
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#索引器封装相关的知识,希望对你有一定的参考价值。
1、学生数据类
public class Student
{
public Student()
{ }
public Student(string no,string name)
{
this.StudentNo = no;
this.StudentName = name;
}
private string studentNo;
private string studentName;
/// <summary>
/// 学号
/// </summary>
public string StudentNo
{
get
{
return studentNo;
}
set
{
studentNo = value;
}
}
/// <summary>
/// 姓名
/// </summary>
public string StudentName
{
get
{
return studentName;
}
set
{
studentName = value;
}
}
}
2、数组
public class MyList
{
/// <summary>
/// 数组元素实际个数
/// </summary>
private int count;
Student[] stus = new Student[4];
#region 元素个数
public int Count
{
get
{
return count;
}
set
{
count = value;
}
}
#endregion
#region 添加元素
public void Add(Student item)
{
if (Count == stus.Length)
{
Student[] newstus = new Student[stus.Length * 2];
stus.CopyTo(newstus, 0);
stus = newstus;
}
stus[count] = item;
count++;
}
#endregion
#region 获取元素
public Student Get(int index)
{
return stus[index];
}
public Student Get(string name)
{
for (int i = 0; i < count; i++)
{
if (stus[i].StudentName == name)
{
return stus[i];
}
}
return null;
}
#endregion
#region 索引器
public Student this[int index]
{
get
{
return stus[index];
}
set { stus[index] = value; }
}
public Student this[string name]
{
get
{
for (int i = 0; i < count; i++)
{
if (stus[i].StudentName == name)
{
return stus[i];
}
}
return null;
}
set
{
for (int i = 0; i < count; i++)
{
if (stus[i].StudentName == name)
{
stus[i] = value;
}
}
}
}
#endregion
}
3、调用
static void Main(string[] args)
{
MyList ml = new c0index.MyList();
ml.Add(new Student("001","aa"));
ml.Add(new Student("002", "bb"));
ml.Add(new Student("003", "cc"));
ml.Add(new Student("004", "dd"));
ml.Add(new Student("005", "ee"));
for (int i = 0; i < ml.Count; i++)
{
Console.WriteLine(ml[i].StudentName);
}
}
以上是关于C#索引器封装的主要内容,如果未能解决你的问题,请参考以下文章