What Is an Indexer?

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:7

lượt xem

What Is an Indexer?

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

một Indexer là gì? indexer An là một mảng thông minh trong cách chính xác giống như một tài sản là một lĩnh vực thông minh. Cú pháp mà bạn sử dụng cho một indexer là chính xác giống như cú pháp bạn sử dụng cho một mảng. Hãy làm việc thông qua một ví dụ.

Chủ đề:

Nội dung Text: What Is an Indexer?

  1. What Is an Indexer? An indexer is a smart array in exactly the same way that a property is a smart field. The syntax that you use for an indexer is exactly the same as the syntax you use for an array. Let's work through an example. First, we'll examine a problem and see a weak solution that doesn't use indexers. Then we'll work through the same problem and look at a better solution that does use indexers. The problem concerns integers, or more precisely, the int type. An Example That Doesn't Use Indexers You normally use an int to hold an integer value. Internally an int stores its value as a sequence of 32 bits, where each bit can be either 0 or 1. Most of the time you don't care about this internal binary representation; you just use an int type as a bucket to hold an integer value. However, sometimes programmers use the int type for other purposes; some programs manipulate the individual bits within an int. (If you are an old C programmer you should feel at home with what follows!) In other words, occasionally a program might use an int because it holds 32 bits and not because it can represent an integer. NOTE Some older programs might use int types to try to save memory. A single int holds 32 bits, each of which can be 1 or 0. In some cases, programmers assigned 1 to indicate a value of true and 0 to indicate false, and then employed an int as a set of Boolean values. For example, the following expression uses the
  2. The trouble with these examples is that although they work, it's not clear why or how they work. They're complicated and the solution is a very low-level one. It fails to create an abstraction of the problem it solves. The Bitwise and Shift Operators You might have noticed some unfamiliar symbols in the expressions shown in these examples. In particular, ~,
  3. And, for example, set the bit at index 6 to true, we'd like to be able to write: bits[6] = true Unfortunately, you can't use the square bracket notation on an int. It only works on an array or on a type that behaves like an array; that is, on a type that declares an indexer. So the solution to the problem is to create a new type that acts like, feels like, and is used like an array of bool variables but is implemented by using an int. Let's call this new type IntBits. IntBits will contain an int value (initialized in its constructor), but the idea is that we'll use IntBits as an array of bool variables. TIP Because IntBits is small and lightweight, it makes sense to create it as a struct rather than as a class. struct IntBits { public IntBits(int initialBitValue) { bits = initialBitValue; } // indexer to be written here private int bits; } To define the indexer, you use a notation that is a cross between a property an an array. The indexer for the IntBits struct looks like this: struct IntBits { ... public bool this [ int index ] { get { return (bits & (1
  4. else bits &= ~(1
  5. When you read an indexer, the compiler automatically translates your array-like code into a call to the get accessor of that indexer. For example, consider the following example: bool peek = bits[6]; This statement is converted into a call to the get accessor for bits, and the value of the index argument is set to 6. Similarly, if you write to an indexer, the compiler automatically translates your array-like code into a call to the set accessor of that indexer, setting the index argument to the specified value. For example, consider the following statement: bits[6] = true; This statement is converted into a call to the set accessor for bits where the value of index is 6. As with ordinary properties, the value you are writing to the indexer (in this case, true) is made available inside the set accessor by using the value keyword. The type of value is the same as the type of indexer itself (in this case, bool). It's also possible to use an indexer in a combined read/write context. In this case, the get and set accessors are used. For example, consider the following statement: bits[6] ^= true; This is automatically translated into: bits[6] = bits[6] ^ true; This code works because the indexer declares both a get and a set accessor. NOTE You're also allowed to declare an indexer that contains only a get accessor (a read-only indexer), or a set accessor (a write-only accessor). Comparing Indexers and Arrays When you use an indexer, the syntax is deliberately very array-like. However, there are some important differences between indexers and arrays: • Indexers can use non-numeric subscripts, whereas arrays can use only integer subscripts: public int this [ string name ] { ... } // okay
  6. TIP Many collection classes, such as Hashtable, that implement an associative lookup based on key/value pairs implement indexers as a convenient alternative to using the Add method to add a new value, and iterating through the Values property to locate a value in your code. For example, instead of this: Hashtable ages = new Hashtable(); ages.Add("John", 41); you can use this: Hashtable ages = new Hashtable(); ages["John"] = 41; • Indexers can be overloaded (just like methods), whereas arrays can't: • public Name this [ PhoneNumber number ] { ... } public PhoneNumber this [ Name name ] { ... } • Indexers can't be used as ref or out parameters, whereas array elements can: • IntBits bits; // bits contains an indexer Method(ref bits[1]); // compile-time error Properties, Arrays, and Indexers It is possible for a property to return an array, but remember that arrays are reference types, so exposing an array as a property makes it possible to accidentally overwrite a lot of data. Look at the following struct that exposes an array property called Data: struct Wrapper { int[] data; ... public int[] Data { get { return this.data; } set { this.data = value; } } } Now consider the following code that uses this property: Wrapper wrap = new Wrapper(); ... int[] myData = wrap.Data;
  7. myData[0]++; myData[1]++; This looks pretty innocuous. However, because arrays are reference types, the variable myData refers to the same object as the private data variable in the Wrapper struct. Any changes you make to elements in myData are made to the data array; the statement myData[0]++ has exactly the same effect as data[0]++. If this is not the intention, it is possible to use the Clone method in the get accessor of the Data property to return a copy of the data array, but this can become very messy and expensive in terms of memory use. Indexers provide a natural solution to this problem—don't expose the entire array as a property, just make its individual elements available through an indexer: struct Wrapper { int[] data; ... public int this [int i] { get { return this.data[i]; } set { this.data[i] = value; } } } The following code uses the indexer in a similar manner to the property shown earlier: Wrapper wrap = new Wrapper(); ... int[] myData = new int[2]; myData[0] = wrap[0]; myData[1] = wrap[1]; myData[0]++; myData[1]++; This time, incrementing the values in the MyData array has no effect on the original array in the Wrapper object. If you really want to modify the data in the Wrapper object, you must write statements such as this: wrap[0]++; This is much clearer, and safer!
Đồng bộ tài khoản