tailieunhanh - Microsoft Visual C# 2010 Step by Step (P8)
Tham khảo sách 'microsoft visual c# 2010 step by step (p8)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 320 Part III Creating Components Note You can declare an indexer that contains only a get accessor a read-only indexer or only 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 such as a string as shown in the following example. Arrays can use only integer subscripts public int this string name . OK . Tip Many collection classes such as Hashtable that implement an associative lookup based on key value pairs implement indexers to provide a convenient alternative to using the Add method to add a new value and as an alternative to iterating through the Values property to locate a value in your code. For example instead of this Hashtable ages new Hashtable John 42 you can use this Hashtable ages new Hashtable ages lohn 42 Indexers can be overloaded just like methods whereas arrays cannot public Name this PhoneNumber number . public PhoneNumber this Name name . Indexers cannot 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 structure that exposes an array property named Data struct Wrapper private int data . public int Data Chapter 16 Using Indexers 321 get return set value Now consider the following code that uses this property Wrapper wrap new Wrapper . int myData 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 structure. Any changes you make to elements in myData are made to the .
đang nạp các trang xem trước