分享

索引器、结构的案列

 紫衣风华 2015-01-19
我下面给你一个详细的例子,包括了你提的2个问题,都有注释,有什么问题Hi我。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Student s1 = new Student(18, "张三");
Student s2 = new Student(17,"李四");
StudentList sl = new StudentList();
sl.Add(s1);
sl.Add(s2);
//调用索引器
Console.WriteLine("我叫{0},今年{1}岁",sl["张三"].name,sl["张三"].age);
Console.ReadKey();
}
}

/// <summary>
/// 定义一个结构,学生
/// </summary>
public struct Student
{
public int age; //年龄
public string name; //姓名
//构造函数,除非不定义,如果定义就必须初始化全部属性
public Student(int age, string name)
{
this.age = age;
this.name = name;
}
}
/// <summary>
/// 定义一个列表
/// </summary>
public class StudentList : List<Student>
{
/// <summary>
/// 定义一个索引器,按名称查找
/// </summary>
/// <param name="name">参数:名字</param>
/// <returns>此名字的学生</returns>
public Student this[string name]//这里注意,参数不一定要是字符串,也可以是其他类型,比如也可以按年龄查找等等。
{
get
{
//遍历所有学生
foreach (Student ms in this)
{
//找到了名字为name值的学生,返回此学生
if (ms.name == name)
{
return ms;
}
}
//default函数用来返回一个类型的默认值,不用深究。
return default(Student);
}
set
{
//遍历所有学生
for (int i = 0; i < this.Count(); i++)
{
//找到了名字为name值的学生,给这个学生重新赋值。
Student ms = this[i];
if (ms.name == name)
{
ms = value;
}
}
}
}
}
}
追问
非常感谢啦,好像明白了许多,但是新的问题又来了,在Program类中,上面的代码里 先是实例化了两个“学生” 值类型对象, 
Student s1 = new Student(18, "张三");
Student s2 = new Student(17,"李四");
StudentList sl = new StudentList();
sl.Add(s1);
sl.Add(s2);
用sl.Add();这里我就不知道了?
class StudentList : List<Student>
List 集合加在那个StudentList 类名 :List<Student>
是什么意思呢?
回答
List<T>是一个泛型类,用来装载限定类型的集合。
<>里的T就代表这个集合中装的数据的类型
比如List<Student>就代表这个集合只能装Student类型
: (冒号)是代表继承,也就是说StudentList 这个类将拥有和List<T>类一样的特性,也是一个能装载数据的集合,这样说明白么?
追问
嗯 明白了,今天在学校刚学了泛型...
foreach (Student ms in this)
{
//找到了名字为name值的学生,返回此学生
if (ms.name == name)
{
return ms;
}
}
实例那化的时候对象存在集合中,Student 这个类里面还有值么,遍历的时候给索引器传sI[“张三”],它是怎么在Student 里面找到得呢
回答
Student这个类里面还有值么?
你想说的是这个类的对象有没有值吧?
当然有值,只要资源没有释放掉就一直有值,和放在哪里没有关系。
sI[“张三”]怎么找到的,就看索引器中get中的内容了,get中不是遍历了整个集合,找到名字和传过来的值(这里就是张三了)一样的Student然后返回了吗?
追问
foreach (Student ms in this)
{
if (ms.name == name)
{
return ms;
}
}
上面这段代码里面的 this ,代表上面呢,我刚才调试的时候鼠标放在this上面的时候,显示的是 Count 2 ,好像是存进去的对象的数量。。。this.里面为上面会有存进去的对象呢?
回答
this关键字在那个类里就代表哪个类的对象,这里的this是在StudentList类中,当然就代表StudentList类的对象,这个类继承自List<T>,所以可以往里面装集合。

这样交流很累,你把问题关掉,加我好友吧,Hi里面聊

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多