This keyword and indexer

Source: Internet
Author: User

First, this keyword

In C #, the This keyword has the following 3 common uses:

1. Use the attribute, instance method, or instance construction method of a class to differentiate between a member name and a local variable (or parameter). The following example declares a class named MyClass, which includes an instance field Myval and an instance constructor with a parameter named Myval, which, in the method, can be semantically distinguished by the member name Myval and the parameter name Myval. (Note: The parameter names and field names are not recommended in actual programming, which reduces the readability of the code, just to illustrate the use of the This keyword).

1     class MyClass 2     {3         //Declare an integer field named "Myval" 4 public        int myval = ten; 5  6         //Declare a constructor with a function named "MyV Al "Parameter 7 public         MyClass (int. myval) 8         {9             //" This "represents the current instance of the MyClass class             // Here you can semantically differentiate member names Myval and parameter names myVal11             this.myval + = myval;12         }13     }

2.this represents the current object, which can be passed as an argument to other methods. For example, the following declares a class MyClass1, which includes an instance member method compute, and compute with a parameter of type MyClass, which participates in the operation of the method.

1     class MyClass1 2     {3         //Declare a computed method with a parameter type of MyClass 4 public         static int Compute (MyClass MC) 5         {6             in T resutl = 0; 7             if (MC! = NULL) 8             {9                 resutl + = mc.myval;10             }11             return resutl;12         }13     }

The following is a declaration of a local variable added to the constructor of the class MyClass, which initializes the value from the computed result of the MyClass1 compute method. You can then pass this as an argument to the calling method:

1     class MyClass 2     {3         //Declare an integer field named "Myval" 4 public        int myval = ten; 5  6         //Declare a constructor that takes a Parameter 7 public         MyClass (int myval) named "Myval" 8         {9             //"This" represents the current instance of the MyClass class             // Here through this can be semantically distinguished member name myval and parameter name myVal11             this.myval + = myval;12             //Use this as an argument to the current object to the Compute method,             int res = Myval + myclass1.compute (this);         }16     }

3. declare the indexer. Next, we analyze the declaration and usage of indexers in the second part.

Also, it should be noted that because static member functions exist at the class level and are not part of an object, there is no this pointer, so the This keyword cannot be used in static methods. It is an error to refer to this in a static method .

Second, indexer

1. Accessing instance members through the point operator

In general, we access the instance members of the class by means of the dot operator ("instance name. Member name"). For example, in this case, the member field is actually assigned a value by calling the property's set accessor, and the value of the member field is read through the get accessor.

1     class Course 2     {3 public         float  Chinese {set; get;} 4 publicly         float Math {set; get;} 5         Public float Englisth {set; get;}  6     } 7  8     Class program 9     {ten         static void Main (string[] args)         {             //declaration of an instance of a course class 13             var course = new Course (); Use the             traditional "instance name. Member name" method to access the member             //assignment of             course. Chinese = 95;18             course. Math = 100;19             course. Englisth = 80;20             //value             Console.WriteLine ("Language: {0}, Math: {1}, English: {2}", course. Chinese, course. Math, course. ENGLISTH);             Console.readkey ();         }24     }

2. Accessing instance members through the indexer

By observing the code in the example above, you can see that all members of the class have the same type string, which can actually be accessed in the same way as an array, so we can provide another way for the class to access the instance members: indexers. The following code adds a string type index to the above course class declaration and accesses the data through an index in the Main method:

 1 class Course 2 {3 public float Chinese {set; get;} 4 public float Math {set; get;} 5         Public float Englisth {set; get;} 6 7//Declaration of an indexer of type float, 8 publicly float This[int Index] 9                     {ten//Set accessor: assignment set12 {14 switch (index) {15 Case 0:16. Chinese = value;17 break;18 case 1:19 this. Math = value;20 break;21 case 2:22 this.                          Englisth = value;23 break;24 default:25//An exception is thrown when the index is out of bounds 26 throw new ArgumentOutOfRangeException (); 27} 28}29//                Get accessor: Value of GET31 {33 switch (index) {34)     Case 0:35 return this. chinese;36 Case 1:37 return this. math;38 Case 2:39 return this.                 englisth;40 default:41 throw new ArgumentOutOfRangeException (); 42         }43}44}45}46 class Program48 {$ static void Main (string[] args) 50             {51//Declaration of an instance of a course class course = new Course (); 53 54//Use indexer to access instance members 55             Assignment Course[0] = 95;57 course[1] = 100;58 course[2] = 80;59//value 60         Console.WriteLine ("Language: {0}, Mathematics: {1}, English: {2}", Course[0], course[1], course[2]); Console.readkey (); 62 }63}

3. What is an index?

The above has already declared and used the index, here the analysis summarizes the concept and the characteristic of the index:

1). The concept of an index

An index is also a class member and must be an instance member because it is a way of accessing an instance member, so it cannot be declared static. Indexes are similar to properties and have get accessors and set accessors. And the index is actually a set of get accessors and set accessors, and the nature of the accessor is the method, so the essence of the indexer is the method. indexers are often declared in types that are primarily used to encapsulate internal collections or arrays.

2). Index Declaration

The index declaration uses the following syntax:

[Access modifier] return value type this [parameter 1, Parameter 2 ...]

{

Get{...}

Set{...}

}

Syntax points: The index name is always this; The index parameter is in the middle of the square brackets; The index has at least one parameter in the parameter list.

3). Set accessor

When an index is used to assign a value, its set accessor is implicitly called, and the set accessor is characterized as follows:

First, its return value type is void.

Second, it has the same argument list as the parameter list declared in the index.

Thirdly, it has an implicit value parameter named value, with the same type of parameter and index.

4). Get accessor

When an index is used to fetch a value, the get accessor is implicitly called, and the Get accessor features the following:

First, it has the same return value type as the index type.

Second, it has the same argument list as the parameter list declared in the index.

5). Security of the Index

When a client accesses a member through an index, some exceptions, such as an index out of bounds, are likely to occur. There are two ways to improve the security of an index:

First, strict access-level control is declared for the index, such as the ability to change the modifier of the set accessor to private.

1             //Set Accessor: Assignment 2             Private set 3             {4                 switch (index) 5                 {6 case                     0:7 this                         . Chinese = value; 8 Break                         , 9 case                     1:10 this                         . Math = value;11                         break;12 case                     2:13 this                         . Englisth = value;14                         break;15                     default:16                         //Index out-of-bounds throws exception when thrown                         new ArgumentOutOfRangeException ();                 }19             }

Second, check the number of members, or throw an exception.

1                        //index out of Bounds throw exception 2                         throw new ArgumentOutOfRangeException ();

6). Index overloading

An index can declare multiple parameters, or it can be overloaded, as long as the argument list is different. The following is an overload that declares several indexes for the course class.

 1 class Course 2 {3 public float Chinese {set; get;} 4 public float Math {set; get;} 5         Public float Englisth {set; get;} 6 7//Declaration of an indexer of type float, 8 publicly float This[int Index] 9                     {ten//Set accessor: assignment set12 {14 switch (index) {15 Case 0:16. Chinese = value;17 break;18 case 1:19 this. Math = value;20 break;21 case 2:22 this.                          Englisth = value;23 break;24 default:25//An exception is thrown when the index is out of bounds 26 throw new ArgumentOutOfRangeException ();}28}29//Get                    Accessor: Value of GET31 {33 switch (index) {34) Case 0:35 return this. chinese;36 Case 1:37 return this. math;38 Case 2:39 return this.                 englisth;40 default:41 throw new ArgumentOutOfRangeException (); 42             }43}44}45 46//Index Reload * Public float this[string name, float val]48 {49                          SET50 {* * switch (name) * Chinese ": 54 This. Chinese = value + val;55 break;56 case "Math":. Math = value + val;58 break;59 case "中文版": this. Englisth = value + val;61 break;62 default:63 throw NE      W ArgumentOutOfRangeException (); 64           }65}66 get67 {70 (name) 69 Case "Chinese": the return this. chinese;72 case "Math": the return of this. math;74 case "中文版": return this.                 englisth;76 default:77 throw new ArgumentOutOfRangeException (); 78 }79}80}81 82//Reload 2: Read-only index protected string This[int Index, string name, BOOL FL ag]84 {set86 {87 88}89}90 91}

Iii. comparison of indexers and attributes

1. The same point

1). Neither the index nor the attributes are stored in the allocated memory location.

2). Both indexes and attributes provide access control for other members of the class.

3). Indexes and properties have get accessors and set accessors, which can declare two accessors at the same time, or they can declare only one of them.

2. Different points

1). Properties typically represent separate data members, whereas indexes represent multiple data members.

2). A property can be declared as either an instance property or a static property, and the index cannot be declared static.

3). The attribute has a concise, auto-implemented property, and the index must be declared intact.

4). Get accessor: The get accessor of the property has no parameters, and the get accessor of the indexer has the same formal parameter list as the indexer.

5). Set accessor: The set accessor of the property contains an implicit value parameter. In addition to the value parameter, the indexer's set accessor has the same formal parameter list as the indexer.

This keyword and indexer

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.