c#屬性和索引器

來源:互聯網
上載者:User
1、屬性
所謂屬性其實就是特殊的類成員,它實現了對私人類域的受控訪問。在C#語言中有兩種屬性方法,其一是get,通過它可以返回私人域的值,其二是set,通過它就可以設定私人域的值。比如說,以下面的代碼為例,建立學生姓名屬性,控制對name欄位的受控訪問:

using System;public class Student{    private string name;    /// <summary>    /// 定義學生的姓名屬性    /// </summary>    public string Name    {        get { return name; }        set { name = value; }    }}class Program{    static void Main(string[] args)    {        Student student = new Student();        student.Name = "Jeff Wong";        Console.WriteLine(student.Name);        Console.Read();    }}

2、索引器
簡單說來,所謂索引器就是一類特殊的屬性,通過它們你就可以像引用數組一樣引用自己的類。顯然,這一功能在建立集合類的場合特別有用,而在其他某些情況下,比如處理大型檔案或者抽象某些有限資源等,能讓類具有類似數組的行為當然也是非常有用的。比如,上例中,我們假設一個班級有若干個學生,構建索引器就可以很方便地調用:

using System;using System.Collections.Generic;public class Student{    public List<Student> listStudents = new List<Student>();    /// <summary>    /// 構建索引器    /// </summary>    /// <param name="i"></param>    /// <returns></returns>    public Student this[int i]    {        get { return listStudents[i]; }        set { listStudents[i] = value; }    }    private string name;    /// <summary>    /// 屬性    /// </summary>    public string Name    {        get { return name; }        set { name = value; }    }    public Student(string name)    {        this.name = name;    }    public Student()    {        this.listStudents.Add(new Student("jeff wong"));        this.listStudents.Add(new Student("jeffery zhao"));        this.listStudents.Add(new Student("terry lee"));        this.listStudents.Add(new Student("dudu"));    }}class Program{    static void Main(string[] args)    {        Student student = new Student();        int num = student.listStudents.Count;        Console.WriteLine("All the students:");        for (int i = 0; i < num; i++)        {            Console.WriteLine(student[i].Name); //通過索引器,取所有學生名        }        //設定索引器的值        student[0].Name = "jeff";        Console.WriteLine("After modified,all the students:");        for (int i = 0; i < num; i++)        {            Console.WriteLine(student[i].Name);         }        Console.Read();    }}

上面代碼中,我們看到索引器的訪問器帶一個參數(參數為整數),其實可以構建多個參數的索引器。還以上述代碼為例,我們要根據學生學號和姓名得到學生的考試總分,修改後代碼如下:

using System;using System.Collections.Generic;public class Student{    public List<Student> listStudents = new List<Student>();    public Student this[int i,string name]    {        get        {            foreach (Student stu in listStudents.ToArray())            {                if (stu.sid == i && stu.name == name) //按照學號和姓名取出學生                {                    return stu;                }            }            return null;        }        set { listStudents[i] = value; }    }    private int sid; //學號    public int Sid    {        get { return sid; }        set { sid = value; }    }    private string name;//姓名    public string Name    {        get { return name; }        set { name = value; }    }    private int score; //總分    public int Score    {        get { return score; }        set { score = value; }    }    public Student(int sid, string name, int score)    {        this.sid = sid;        this.name = name;        this.score = score;    }    public Student()    {        this.listStudents.Add(new Student(1, "jeff wong", 375));        this.listStudents.Add(new Student(2,"jeffery zhao",450));        this.listStudents.Add(new Student(3,"terry lee",400));        this.listStudents.Add(new Student(4,"dudu",500));    }}class Program{    static void Main(string[] args)    {        Student student = new Student();        Student stu = student[1, "jeff wong"];        Console.WriteLine("student number:" + stu.Sid + ",name:" + stu.Name + ",score:" + stu.Score);        Console.Read();    }}

3、總結:
<1>、

屬性的定義:
存取修飾詞 傳回型別 屬性名稱


get{語句集合}
set{語句集合}

索引器的定義:

存取修飾詞 傳回型別 this[參數類型 參數...]

get{語句集合}
set{語句集合}

<2>、

索引器使得對象可按照與數組相似的方法進行索引。
this 關鍵字用於定義索引器。
get 訪問器傳回值。set 訪問器分配值。
value 關鍵字用於定義由 set 索引器分配的值。
索引器不必根據整數值進行索引,由你決定如何定義特定的尋找機制。
索引器可被重載。
<3>、屬性和索引器的主要區別:
a、類的每一個屬性都必須擁有唯一的名稱,而類裡定義的每一個索引器都必須擁有唯一的簽名(signature)或者參數列表(這樣就可以實現索引器重載)。
b、屬性可以是static(靜態)而索引器則必須是執行個體成員。
<4>、索引器重載執行個體:

using System;using System.Collections.Generic;public class Student{    public List<Student> listStudents = new List<Student>();    public Student this[int i,string name]    {        get        {            foreach (Student stu in listStudents.ToArray())            {                if (stu.sid == i && stu.name == name) //按照學號和姓名取出學生                {                    return stu;                }            }            return null;        }        set { listStudents[i] = value; }    }    /// <summary>    /// 索引器重載    /// </summary>    /// <param name="i"></param>    /// <returns></returns>    public Student this[int i] //i從0開始    {        get { return listStudents[i]; }        set { listStudents[i] = value; }    }    private int sid; //學號    public int Sid    {        get { return sid; }        set { sid = value; }    }    private string name;//姓名    public string Name    {        get { return name; }        set { name = value; }    }    private int score; //總分    public int Score    {        get { return score; }        set { score = value; }    }    public Student(int sid, string name, int score)    {        this.sid = sid;        this.name = name;        this.score = score;    }    public Student()    {        this.listStudents.Add(new Student(1, "jeff wong", 375));        this.listStudents.Add(new Student(2,"jeffery zhao",450));        this.listStudents.Add(new Student(3,"terry lee",400));        this.listStudents.Add(new Student(4,"dudu",500));    }}class Program{    static void Main(string[] args)    {        Student student = new Student();        Student stu = student[1, "jeff wong"];        Console.WriteLine("student number:" + stu.Sid + ",name:" + stu.Name + ",score:" + stu.Score);              Console.WriteLine("all the students:");        for (int i = 0; i < student.listStudents.Count; i++)        {            Console.WriteLine("student number:" + student[i].Sid + ",name:" + student[i].Name + ",score:" + student[i].Score);        }        Console.Read();    }}



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.