C#中如何应用索引器 ( How to use Indexers )
2013-07-03 16:49
281 查看
C#中索引器是个好东西, 可以允许类或者结构的实例像数组一样进行索引。 在foreach或者直接索引时很有用。
使用索引器可以简化客户端代码, 即调用者可以简化语法,直观理解类及其用途。索引器只能根据声明的形参类型及数量进行区别, 形参命名不能作为区分。
概述:使用索引器可以用类似于数组的方式为对象建立索引。
get 访问器返回值。 set 访问器分配值。
this 关键字用于定义索引器。
value 关键字用于定义由 set 索引器分配的值。
索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
索引器可被重载。
索引器可以有多个形参,例如当访问二维数组时。
代码片段:
class SampleCollection<T> { // Declare an array to store the data elements. private T[] arr = new T[100]; // Define the indexer, which will allow client code // to use [] notation on the class instance itself. // (See line 2 of code in Main below.) public T this[int i] { get { // This indexer is very simple, and just returns or sets // the corresponding element from the internal array. return arr[i]; } set { arr[i] = value; } } } // This class shows how client code uses the indexer.class Program { static void Main(string[] args) { // Declare an instance of the SampleCollection type. SampleCollection<string> stringCollection = new SampleCollection<string>(); // Use [] notation on the type. stringCollection[0] = "Hello, World"; System.Console.WriteLine(stringCollection[0]); } } // Output:// Hello, World.
相关文章推荐
- C#中如何应用索引器 ( How to use Indexers )
- C#中如何应用索引器 ( How to use Indexers )
- 在iPhone应用中如何使用随机数(How to Use Random Numbers in Your iPhone App)
- Regular Expression in C# - How to make use of Expresso
- How to write a DCOM server in C# 如何用C#编写DCOM服务器
- 如何使用代码美化器Uncrustify (How to use code beautifier Uncrustify)
- How to use Console.WriteLine in ASP.Net (C#) during debug?
- 如何使用spring将service层注入到servlet中去(how to use Spring to inject ur service layer into the servlet )
- How to use bitBucket with EGit in Eclipse,如何在Eclipse中使用bitbucket远程仓库
- How to get camped network type name - Android应用如何获得Phone当前注册的网络类型
- 如何用gcc/g++编译生成so链接库,以及how to use .so
- 【翻译】C# Tips & Tricks: Weak References - When and How to Use Them
- How to use toolbar control on dialog using CToolBar class in VC++ - VC++ 中用CToolBar 类如何使用ToolBar控件
- 如何使用spy ++ (How to use Spy ++)
- How to use FTP via Windows Explorer(如何使用资源管理器访问 ftp)
- 如何使用spy ++ (How to use Spy ++)
- 为何以及如何使用Netlink Socket ( Why and How to Use Netlink Socket)
- All-In-One Code Framework(AIO): 如何使用C#编写进程外的COM组件 (How to write an out-of-proc COM server in C#)
- (译)如何使用SocketAsyncEventArgs类(How to use the SocketAsyncEventArgs class)
- How to use ComboBox Control in VC++ - 在VC中如何使用 ComboBox 控件