C # Properties and indexers

Source: Internet
Author: User
1. Properties
The so-called attribute is actually a special class member that implements controlled access to the private class domain. There are two property methods in the C # language, one is get, through which you can return the value of a private domain, and the other is set, through which you can set the value of a private domain. For example, use the following code, for example, to create a student name attribute that controls controlled access to the Name field:

Using System;public class student{    private string name;    <summary>///    Define student's name attribute///    </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. Indexer
Simply put, indexers are a special kind of property that allows you to refer to your class as if you were referencing an array. Obviously, this feature is particularly useful when creating collection classes, and in some other cases, such as working with large files or abstracting some finite resources, it is certainly useful to have classes that behave like arrays. For example, in the example above, we assume that a class has several students and that building an indexer makes it easy to invoke:

Using system;using System.collections.generic;public class student{public list<student> liststudents = new List& Lt    Student> (); <summary>///build indexer///</summary>//<param name= "I" ></param>//<returns&gt        ;</returns> public Student This[int i] {get {return liststudents[i];}    set {Liststudents[i] = value;}    } private string name;        <summary>//Properties///</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); Through the indexer, take all student names}//Set the indexer value 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 (); }}

In the code above, we see an indexer with an accessor with a parameter (an integer argument) that can actually build multiple parameters. Also take the above code as an example, we have to according to the student number and name to get the student's test scores, modified code as follows:

Using system;using System.collections.generic;public class student{public list<student> liststudents = new List& Lt    Student> ();             Public Student this[int i,string name] {get {foreach (Student stu in Liststudents.toarray ())                    {if (Stu.sid = = I && stu.name = = name)//Remove students by number and name {                return Stu;        }} return null;    } set {Liststudents[i] = value;} } private int sid;        Study number public int sid {get {return Sid;}    set {sid = value;}        } private string name;//name public string Name {get {return name;}    set {name = value;} } private int score;        Total 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. Summary:
<1>,

The definition of the property:
Access modifier return Type property name


get{Statement Collection}
set{Statement Collection}

The definition of an indexer:

Access modifier return type this[parameter type parameter ...]

get{Statement Collection}
set{Statement Collection}

<2>,

Indexers enable an object to be indexed in a similar way to an array.
The This keyword is used to define indexers.
The get accessor returns a value. The set accessor assigns a value.
The value keyword is used to define the values assigned by the set indexer.
Indexers do not have to be indexed by integer values, and you decide how to define a specific lookup mechanism.
Indexers can be overloaded.
The main differences between <3>, attributes, and indexers:
A, each property of a class must have a unique name, and each indexer defined in the class must have a unique signature (signature) or a list of parameters (so that indexer overloading can be implemented).
B, the property can be static and the indexer must be an instance member.
<4> overloaded instances of indexers:

Using system;using System.collections.generic;public class student{public list<student> liststudents = new List& Lt    Student> ();             Public Student this[int i,string name] {get {foreach (Student stu in Liststudents.toarray ())                    {if (Stu.sid = = I && stu.name = = name)//Remove students by number and name {                return Stu;        }} return null;    } set {Liststudents[i] = value;} }///<summary>//Indexer reload///</summary>//<param name= "I" ></param>//<retur        ns></returns> public Student This[int i]//i starting from 0 {get {return liststudents[i];}    set {Liststudents[i] = value;} } private int sid;        Study number public int sid {get {return Sid;}    set {sid = value;}        } private string name;//name public string Name {get {return name;} set {name = value;}   } private int score;        Total 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 (); }}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.