我下面給你一個詳細的例子,包括了你提的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); //調(diào)用索引器 Console.WriteLine("我叫{0},今年{1}歲",sl["張三"].name,sl["張三"].age); Console.ReadKey(); } }
/// <summary> /// 定義一個結(jié)構(gòu),學(xué)生 /// </summary> public struct Student { public int age; //年齡 public string name; //姓名 //構(gòu)造函數(shù),除非不定義,如果定義就必須初始化全部屬性 public Student(int age, string name) { this.age = age; this.name = name; } } /// <summary> /// 定義一個列表 /// </summary> public class StudentList : List<Student> { /// <summary> /// 定義一個索引器,按名稱查找 /// </summary> /// <param name="name">參數(shù):名字</param> /// <returns>此名字的學(xué)生</returns> public Student this[string name]//這里注意,參數(shù)不一定要是字符串,也可以是其他類型,比如也可以按年齡查找等等。 { get { //遍歷所有學(xué)生 foreach (Student ms in this) { //找到了名字為name值的學(xué)生,返回此學(xué)生 if (ms.name == name) { return ms; } } //default函數(shù)用來返回一個類型的默認值,不用深究。 return default(Student); } set { //遍歷所有學(xué)生 for (int i = 0; i < this.Count(); i++) { //找到了名字為name值的學(xué)生,給這個學(xué)生重新賦值。 Student ms = this[i]; if (ms.name == name) { ms = value; } } } } } }
追問
非常感謝啦,好像明白了許多,但是新的問題又來了,在Program類中,上面的代碼里 先是實例化了兩個“學(xué)生” 值類型對象, 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就代表這個集合中裝的數(shù)據(jù)的類型 比如List<Student>就代表這個集合只能裝Student類型 : (冒號)是代表繼承,也就是說StudentList 這個類將擁有和List<T>類一樣的特性,也是一個能裝載數(shù)據(jù)的集合,這樣說明白么?
追問
嗯 明白了,今天在學(xué)校剛學(xué)了泛型... foreach (Student ms in this) { //找到了名字為name值的學(xué)生,返回此學(xué)生 if (ms.name == name) { return ms; } } 實例那化的時候?qū)ο蟠嬖诩现?,Student 這個類里面還有值么,遍歷的時候給索引器傳sI[“張三”],它是怎么在Student 里面找到得呢
回答
Student這個類里面還有值么? 你想說的是這個類的對象有沒有值吧? 當(dāng)然有值,只要資源沒有釋放掉就一直有值,和放在哪里沒有關(guān)系。 sI[“張三”]怎么找到的,就看索引器中g(shù)et中的內(nèi)容了,get中不是遍歷了整個集合,找到名字和傳過來的值(這里就是張三了)一樣的Student然后返回了嗎?
追問
foreach (Student ms in this) { if (ms.name == name) { return ms; } } 上面這段代碼里面的 this ,代表上面呢,我剛才調(diào)試的時候鼠標(biāo)放在this上面的時候,顯示的是 Count 2 ,好像是存進去的對象的數(shù)量。。。this.里面為上面會有存進去的對象呢?
回答
this關(guān)鍵字在那個類里就代表哪個類的對象,這里的this是在StudentList類中,當(dāng)然就代表StudentList類的對象,這個類繼承自List<T>,所以可以往里面裝集合。
這樣交流很累,你把問題關(guān)掉,加我好友吧,Hi里面聊
|