您的位置:首页 > 编程语言 > C#

The indexer in C#(C#中的索引器)

2009-10-29 00:27 465 查看
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

In the following example, a generic class is defined and provided with simple get and set accessor methods as a means of assigning and retrieving values. The Program class creates an instance of this class for storing strings.

class SampleCollection<T>

// This class shows how client code uses the indexer.
class Program
//declaration:
class Mlass

//usage:
Mlass m = new Mlass();
m[2, 2] = 3;
Console.WriteLine(m[2, 2]);

Addition

1. Just like any other class members, indexers can also participate in inheritance. A base class indexer is inherited to the derived class.

2. A Base class indexer can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

3. An indexer inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract indexer in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.

  If the abstract class contains only set accessor, we can implement only set in the derived class.

Go to my home for more posts
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: