Do not decide indexer easy to use (Indexer tutorial Chinese version):)

Source: Internet
Author: User
Tags count implement integer
Tutorial | The Chinese lesson describes how to declare an index in a class of C # so that classes can be accessed like arrays, so instances of classes can use the
Array access operator [] to access the class object.
Defining an index in C # and defining an operator [] in C + + is similar. For those that encapsulate an array or use it a bit like a set
class, you can use the index so that the user can access the class using the syntax to access the array.
For example, suppose you want to define a class that makes a file like a byte array. If the file is very large, put
It's not practical to read the entire file into memory, especially if you want to read and write only a small subset of bytes.
this. A class Filebytearray is defined here to make the file look like an array, but in fact only
Bytes are read and write to the file input and output operation.

The following shows how to define an indexed property.

Example

In this example, Filebytearray makes access to a file like a byte array. Reverse class to put the bytes of the file
Upside down. You can experiment with the following procedure itself, perform it two times and get back to the status quo.

M://Indexers\indexer.cs
001:using System;
002:using System.IO;
003:
004://Class to provide access to a large file
005://As if it were a byte array.
006:public class Filebytearray
007: {
008:stream Stream; Holds the underlying stream
009://Used to access the file.
010://Create A new Filebytearray encapsulating a particular file.
011:public Filebytearray (String fileName)
012: {
013:stream = new FileStream (FileName, FileMode.Open);
014:}
015:
016://Close the stream. This should is the last thing done
017://When you are finished.
018:public void Close ()
019: {
020:stream. Close ();
021:stream = null;
022:}
023:
024://Indexer to provide read/write access to the file.
025:public byte This[long index]//Long is a 64-bit integer
026: {
027://Read One byte at offset index and return it.
028:get
029: {
030:byte[] buffer = new BYTE[1];
031:stream. Seek (index, seekorigin.begin);
032:stream. Read (buffer, 0, 1);
033:return Buffer[0];
034:}
035://Write One byte at offset index and return it.
036:set
037: {
038:byte[] buffer = new Byte[1] {value};
039:stream. Seek (index, seekorigin.begin);
040:stream. Write (buffer, 0, 1);
041:}
042:}
043:
044://Get the total length of the file.
045:public Long Length
046: {
047:get {
048:return Stream. Seek (0, seekorigin.end);
049:}
050:}
051:}
052:
053://Demonstrate the Filebytearray class.
054://Reverses the bytes in a file.
055:public class Reverse
056: {
057:public static void Main (string[] args)
058: {
059://Check for arguments.
060:if (args. Length = = 0)
061: {
062:console.writeline ("indexer");
063:return;
064:}
065:
066:filebytearray file = new Filebytearray (args[0]);
067:long len = file. Length;
068:
069://Swap bytes in the file to reverse it.
070:for (Long i = 0; i < LEN/2; ++i)
071: {
072:byte T;
073:
074://Note that indexing the "file" variable invokes the
075://Indexer on the Filebytestream class, which reads
076://And writes the bytes in the file.
077:t = File[i];
078:file[i] = file[len-i-1];
079:file[len-i-1] = t;
080:}
081:
082:file. Close ();
083:}
084:}

Run results

Test the program with the text file below.

Indexers\test.txt
public class Hello1
{
public static void Main ()
{
System.Console.WriteLine ("Hello, world!");
}
}

Compile and run the program as follows:

Indexer Test.txt
Type Test.txt

will produce the following display:

}
}
;) "!dlrow, Olleh" (EniLetirW.elosnoC.metsyS
{
) (Niam Diov citats Cilbup
{
1olleH Ssalc Cilbup
Txt.tset\srexedni//

[Code Discussion]

* Because the index uses the operator [], be careful to use the keyword this when declaring, without a name.
* In the above example, a subscript is defined as a long integer, and the return value is the index of the byte, which defines the code from a
A byte is read in the file, and the code is defined in the set to write a byte to a file.
* An index must have at least one parameter. Sometimes you can define multiple parameters, like a multidimensional virtual array, but this
The situation is very rare. In addition, although integral parameters are the most common, the parameters of an index can be of any type. Standard
The dictionary class provides an index in which the parameter is object.
* Although indexing is a very powerful feature, it is only when access with an array form has an exact meaning
appropriate. For example, the following is an inappropriate example.

Class Employee
{
VERY Bad style:using a indexer to access
The salary of an employee.
Public double this[int Year]
{
Get
{
Return to employee ' s salary for a given year.
}
}
}

Take a closer look.

* Indexes can be overloaded (overload) or overwritten (Override). (discussed in detail later)

[Advanced Topics]
How do I create an "indexed property" (Indexed)?

Sometimes a class can be viewed as a different kind of collection from a different perspective. A technique called indexed attributes
You can make this object happen.
Simply put, literally, we can understand that indexed attributes, first of all, are an attribute field, and secondly, it is also an index. Give me A
example, suppose you want to write a class document that encapsulates a piece of text in order to be able to easily check the spelling so that you
You can think of this text as an array of multiple words or an array of multiple statements. Most simply, you may want to
Write the code to check the spelling,

Document d = new document ();
// ...
for (int i = 0; i < D.words.count; ++i)
{
if (d.words[i] = = "Peter")
D.words[i] = "Joe";
}
for (int i = 0; i < D.sentences.count; ++i)
{
if (d.sentences[i] = = "Elvis is the King.")
D.sentences[i] = "Eric Clapton is a guitar god";
}

The following code shows how to implement such a class. To implement an indexed property, you should note that this code defines a
A nested class that contains a reference to the main class instance inside the nested class. A read-only domain is defined in the main class to access nested classes
The defined "virtual array", which is the indexed property.

public class Document
{
public struct wordcollection
{
ReadOnly document document; The containing document

Internal Wordcollection (Document D)
{
Document = D;
}

public string This[int Indexer]
{
Get
{
return document. Getnthword (indexer);
}
Set
{
Document. Setnthword (indexer, value);
}
}
public int Count
{
Get
{
return document. CountWords ();
}
}
}

public struct sentencecollection
{
ReadOnly document document; The containing document

Internal Sentencecollection (Document D)
{
Document = D;
}

public string This[int Indexer] {
Get
{
return document. Getnthsentence (indexer);
}
Set
{
Document. Setnthsentence (indexer, value);
}
}
public int Count
{
Get
{
return document. Countsentences ();
}
}
}

Because the types of the fields have indexers,
These fields appear as "Indexed properties"
Public ReadOnly wordcollection Words;
Public readonly sentencecollection sentences;

Public Document ()
{
Words = new Wordcollection (this);
sentences = new Sentencecollection (this);
}

private string Getnthword (int index)
{
/* ... */
Return "";
}
private void Setnthword (int index, string w)
{
/* ... */
}
private int CountWords ()
{
/* ... */
return 0;
}
private string getnthsentence (int index)
{
/* ... */
Return "";
}

private void setnthsentence (int index, string s)
{
/* ... */
}
private int countsentences ()
{
/* ... */
return 0;
}
}

Note: Use this technique with care! You can't use it. Only when the array abstraction has a specific meaning and can make your code
When you are clearer, you should use indexes or indexed properties.




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.