C # Getting Started Classic (fifth edition) learning notes (iv)

Source: Internet
Author: User

---------------collection, comparison, and transformation---------------

Arrays in C # are implemented as instances of the System.Array class, which are a type in the collection class (Collection Classes).

Collection classes are typically used to work with lists of objects, mostly by implementing interfaces in the System.Collections namespace.

Several interfaces in the System.Collections namespace provide basic collection functionality:

1) IEnumerable can iterate over the items in the collection.

2) ICollection (inherited from IEnumerable) can get the number of items in the collection and can copy items into a simple array type.

3) IList (inherited from IEnumerable and ICollection) provides a list of items for the collection, allows access to these items, and provides some other basic functionality related to the item list

4) IDictionary (inherited from IEnumerable and ICollection) is similar to IList, but provides a list of items that can be accessed through key values rather than indexes.

The System.Array class implements IList, ICollection, and IEnumerable, but does not support some of the more advanced features of IList, which represent a fixed-size list of items.

Array initialization requires a fixed size, and the ArrayList collection is not

animal[] Animalarray = new animal[2];

ArrayList animalarraylist = new ArrayList ();

This class also has two constructors:

1. Copy the existing set as a parameter into the new instance

2, set the capacity of the collection with an int parameter, but the actual content will increase automatically when it exceeds the capacity.

Initializing an array, you need to give the project an initialized object such as:

1 New Cow ("Deirdre"); 2 animalarray[0] = myCow1; 3 animalarray[1new Chicken ("Ken");

You can initialize an array in either of these ways

For ArrayList collections, new items need to be added with the Add () method
For example:

1 New Cow ("Hayley"); 2 Animalarraylist.add (myCow2); 3 animalarraylist.add (new Chicken ("Roy"));

After you have finished adding items, you can rewrite them with the same syntax as the array
For example:

animalarraylist[1new Chicken ("Roy2")

Array arrays and ArrayList collections both support the foreach structure to iterate
For example:

1 foreach inch Animalarray) 2 {3  } 4  foreach inch animalarraylist) 5 {6  

Array array Gets the number of items using the Length property
For example:

Int

ArrayList Collection use the Count property to get the number of items

Int

Array arrays are strongly typed and can be used to store items directly using the type of the array
That is, the properties and methods of the project can be accessed directly
For example:
For an array of type animal, the Feed () is a method of class animal

animalarray[0]. Feed ();

However, for a method of a class animal derived class, it cannot be called directly and requires casting

((Chicken) animalarray[1

Delete items using the Remove () and RemoveAt () methods
Remove removes the first occurrence of a specific object from the ArrayList (parameter is a specific object)
RemoveAt removes the element at the specified index of the ArrayList (parameter is index value) and causes the other items to move one position in the array
Use the AddRange () and Insertrange () methods to add multiple items at once
AddRange add ICollection elements to the end of ArrayList
Insertrange inserts an element from the collection into the ArrayList at the specified index. For example:

Use the IndexOf () method to get the index value of the specified item
IndexOf returns the zero-based index of the first occurrence of a value in the ArrayList or part of it.
option can be accessed directly by index value
For example:

int IIndex =  

Defining collections
Derive your collection from System.Collections.CollectionBase, an abstract class that provides many of the implementation methods of the collection class
CollectionBase class with Ieumerable, ICollection, and IList interfaces
CollectionBase provides two protected properties that access the stored object itself, lists and innerlist,list can access the item through the IList interface, and Innerlist is the ArrayList object used to store the item
Example of a collection class definition:

1  Public classAnimals:collectionbase2  {3       Public voidAdd (Animal newanimal)4      {5 List.add (newanimal);6      }7       Public voidRemove (Animal oldanimal)8      {9 List.remove (oldanimal);Ten      } One       PublicAnimals () {} A}

Implementing code processing objects using ArrayList

 1  Animals animalcollection = new  Span style= "color: #000000;" > Animals ();  2  animalcollection.add (new  Cow ( " cow1  "   3  foreach  (Animal myanimal in   animalcollection)  4   { 5  Console.WriteLine ( " {0} {1}   " ,myanimal.tostring (), Myanimal.name);  6 } 

Cannot use animalcollection[0]. Feed (); Because there is no index symbol
The index can be added to the class to provide an array-like access, for example:

1  Public classAnimals:collectionbase2  {3       PublicAnimal This[intAnimalindex]4      {5          Get{return(Animal) list[animalindex];}6          Set{List[animalindex] =value;}7      }8}


This allows you to use animalcollection[0] that cannot be used above. Feed ();

Keyword Value collection and IDictionary

As with the collection of indexes, a base class can be used to simplify the implementation of the IDictionary interface, DictionaryBase, which also implements IEnumerable and ICollection

An example of a keyword value collection:

 Public classAnimals:dictionarybase { Public voidADD (stringnewid,animal Newanimal)     {Dictionary.add (newid,newanimal); }      Public voidRemove (stringanimalid)     {Dictionary.remove (animalid); }      PublicAnimals () {} PublicAnimal This[stringAnimalid] {         Get{return(Animal) dictionary[animalid];} Set{Dictionary[animalid] =value;} } }

The dictionary collection has a member dictionary that inherits from DictionaryBase, which is a IDictionary interface
Use the foreach and DictionaryBase derived classes to provide a dictionaryentry structure, for example:

foreach inch animalcollection) {     Console.WriteLine ("{0} {1}", MyEntry.Value.ToString (), ((Animal) Myentry.value). Name); }

If you want to extract the animal object directly from foreach, the simplest way is to implement an iterator

Iterators
The IEnumerable interface is responsible for using the Foreach Loop, in which the process of iterating through the collection Collectionobject is as follows:
1) Call Collectionobject.getenumerator () to return a IEnumerator reference, which can be obtained through the implementation code of the IEnumerable interface, but this is optional.
2) Call the MoveNext () method of the returned IEnumerator interface.
3) if the MoveNext () method returns True, a reference to the object is obtained using the current property of the IEnumerator interface for the Foreach loop.
4) Repeat the previous two steps, knowing that the MoveNext () method returns False, and the loop stops at this time
Therefore, in order to perform these operations in a class, you must override several methods, track the index, maintain the current property, and perform some other operations.
A simpler alternative is to use an iterator, which is a block of code that provides in order all the values to be used in the Foreach loop. In general, this block of code is a method, but you can also use property accessors and other blocks of code as iterators.
1) If you want to iterate over a class, you can use the method GetEnumerator (), whose return type is Ienmerator
2) If you want to iterate over a class member, such as a method, use the IEnumerable
In the iterator block, use the yield keyword to select the value you want to use in the Foreach Loop, as in the following example:

 Public StaticIEnumerable SimpleList () {yield return "String 1"; yield return "String 2"; yield return "String 3"; }  Public Static voidTest () {foreach(stringIteminchSimpleList ())     {Console.WriteLine (item); } console.readkey (); }

SimpleList () is an iterator block, and the return type within the iterator block must be the same, otherwise an error type conversion exception occurs.
When a yield break is encountered in an iterator, the iterator handles an immediate interruption when this statement occurs.

Shallow copy and deep copy
To be superficial, a shallow copy is similar to a reference type, and a deep copy is similar to a value type.
Shallow copy refers to a shared entity between a source object and a Copy object, which simply refers to a variable that is equivalent to copying a shortcut.
Deep copy refers to the fact that the source object and the copied object are independent of each other, and changing one object does not make an impression on the other, which is equivalent to copying the file itself.
The MemberwiseClone method creates a shallow copy by creating a new object and then copying the non-static field of the current object to the new object. If the field is of value type, a bitwise copy of the field is performed. If the field is a reference type, the referenced object is copied and not copied, so the original object and its replica refer to the same object. Deep replication, that is, the implementation of the ICloneable interface. ICloneable can be used for deep copy and shallow copy.
To illustrate:

 Public class Content {     publicint  Val;}

Shallow copy (shallow copy)

 Public class shallowcopy {     publicnew  Content ();       Public Shallowcopy (int  newval)     {         = newval;     }       Public Object getcopy ()     {         return  memberwiseclone ();     }}

Deep copy

 Public class deepcopy:icloneable {     publicnew  Content ();       Public Deepcopy (int  newval)     {         = newval;     }       Public Object Clone ()     {         new  deepcopy (mycontent.val);          return Cloner;     

C # Getting Started Classic (fifth edition) learning notes (iv)

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.