Chapter 2 Collection, comparison, and conversion (C # Getting Started classic version 11th ),

Source: Internet
Author: User

Chapter 2 Collection, comparison, and conversion (C # Getting Started classic version 11th ),

1. Set

There are some restrictions on data. The most intolerable thing is that once an array is created, the size of the array is fixed and cannot be added. The set contains the functions of the array, and you can add or delete element items at will. There are other functions.

The functions of a collection are mainly implemented through interfaces, which are included in the System. Collections namespace.

Mainly include:

  • IEnumerable can iterate element items in a set
  • ICollection (inherited from IEnumerable) can obtain the number of element items in the collection, and copy the element items to a simple array type.
  • IList (inherited from IEnumerable and ICollection) provides a list of element items in the collection, allows access to these items, and provides other basic functions related to the element item list.
  • IDictionary (inherited from IEnumerable and ICollection) is similar to IList, but provides a list of element items that can be accessed through the key value.

(1) System. Array and System. Collections. ArrayList

 1 class Program 2     { 3         static void Main(string[] args) 4         { 5             Console.WriteLine("Create an Array type collection of Animal " + 6                 "objects and use it:"); 7             Animal[] animalArray = new Animal[2]; 8             Cow myCow1 = new Cow("Deirdre"); 9             animalArray[0] = myCow1;10             animalArray[1] = new Chicken("Ken");11 12             foreach (Animal myAnimal in animalArray)13             {14                 Console.WriteLine("New {0} object added to Array collection, " +15                     "Name = {1}", myAnimal.ToString(), myAnimal.Name);16             }17 18             Console.WriteLine("Array collection contains {0} objects.", animalArray.Length);19             animalArray[0].Feed();20             ((Chicken)animalArray[1]).LayEgg();21             Console.WriteLine();22 23             Console.WriteLine("Create an ArrayList type collection of Animal " +24                 "objects and use it:");25             ArrayList animalArrayList = new ArrayList();26             Cow myCow2 = new Cow("Hayley");27             animalArrayList.Add(myCow2);28             animalArrayList.Add(new Chicken("Roy"));29 30             foreach (Animal myAnimal in animalArrayList)31             {32                 Console.WriteLine("New {0} object added to ArrayList collection," +33                     " Name = {1}", myAnimal.ToString(), myAnimal.Name);34             }35             Console.WriteLine("ArrayList collection contains {0} objects.", animalArrayList.Count);36             ((Animal)animalArrayList[0]).Feed();37             ((Chicken)animalArrayList[1]).LayEgg();38             Console.WriteLine();39 40             Console.WriteLine("Additional manipulation of ArrayList:");41             animalArrayList.RemoveAt(0);42             ((Animal)animalArrayList[0]).Feed();43             animalArrayList.AddRange(animalArray);44             ((Chicken)animalArrayList[2]).LayEgg();45             Console.WriteLine("The animal called {0} is at index {1}.",46                 myCow1.Name, animalArrayList.IndexOf(myCow1));47             myCow1.Name = "Janice";48             Console.WriteLine("The animal is now called {0}.",49                 ((Animal)animalArrayList[1]).Name);50             Console.ReadKey();51         }52     }

The System. Array class can only fix the Array size during initialization, for example:

Animal [] animalArray = new Animal [2];

The System. Collections. ArrayList class is:

ArrayList animalArrayList = new ArrayList (); // you can set the capacity, but it is automatically doubled when it is exceeded.

In simple Array, it is strongly typed. In this example, It is Animal type, while in ArrayList it is System. Object.

The System. Array class and ArrayList both implement the IEnumerable interface, so you can iterate in foreach.

(2) define a set --- create your own strongly typed set

Generally, a set is derived from a class, such as the System. Collections. CollectionBase class. This abstract class provides a large amount of implementation code for the Collection class, including the IEnumerable, ICollection, and Ilist interfaces.

The CollectionBase class provides two protected attributes to access the storage object itself. List can be accessed through the IList interface, while InnerList can be used to store the ArrayList object of the item.

 1 public class Animals:CollectionBase 2     { 3         public void Add(Animal newAnimal) 4         { 5             List.Add(newAnimal); 6         } 7         public void Remove(Animal oldAnimal) 8         { 9             List.Remove(oldAnimal);10         }11         public Animals()12         {13 14         }15     }

(3) index Operator

The Set Animals defined above cannot access element items according to indexes like animalCollection [0]. Feed (). The index character must be used.

An index is actually a special type of attribute, which can be added to a class and provide access similar to an array.

1 public Animal this [int animalIndex] // this keyword is used together with the parameter in square brackets, for example, MyAnimals [0]. 2 {3 get {return (Animal) List [animalIndex];} 4 set {List [animalIndex] = value;} 5}
 

Summary: You can use CollectionBase to create your own strongly typed collection, which combines the strong typing of the System. Array class and the advantages of multiple list operation methods of System. Collections. ArrayList, which is more convenient. However, type conversion still occurs internally.

(4) Key set and IDictionary

Similar to the IList interface, the IDictionary interface indexes the list of access items through a digital index. Similarly, there is a base class that implements the IDictionary interface, DictionaryBase.

  

 1 public class Animals:DictionaryBase 2     { 3         public void Add(string newID,Animal newAnimal) 4         { 5             Dictionary.Add(newID, newAnimal); 6         } 7         public void Remove(string animalID) 8         { 9             Dictionary.Remove(animalID);10         }11         public Animals()12         { }13 14         public Animal this[string animalID]15         {16             get { return (Animal)Dictionary[animalID]; }17             set { Dictionary[animalID] = value; }18         }19     }

However, there is another difference between a set based on DictionaryBase and a set based on CollectionBase, that is, the foreach method is slightly different. A collection based on CollectionBase can directly extract Animal objects from the collection, while a collection using foreach and DictionaryBase requires a DictionaryEntry structure to achieve similar results.

  

1             foreach (DictionaryEntry myEntry in animalCollection)2             {3                 Console.WriteLine("New {0} object added to custom collection, " +4                     "Name = {1}", myEntry.Value.ToString(), ((Animal)myEntry.Value).Name);5             }

(5) iterator

An iterator is defined as a code block that provides all values to be used in a foreach loop in order. The return types of the iterator code block are IEnumerable and IEnumerator.

To iterate a class, use the GetEnumerator () method. The return type is IEnumerator.

If you want to iterate a class member, use IEnumerable.

The yield keyword is used here, but it is not described in detail in the book.

(6) Deep Replication

The so-called deep replication and shortest replication have no difference in the value type. They all copy a value. In terms of the reference type, shortest replication is the same reference of the replication object, after the copy changes, the source will also change. However, deep replication is different. The content of the Copied object (including fields) is referenced differently. When the copy changes, the source remains unchanged.

 

2. Comparison

(1) type comparison

A. binning and unpacking

Binning refers to converting the value type to the System. Object type or to the interface type implemented by the value type. Reference of a copy that contains a value type variable.

Unpacking is the opposite process.

The binning is performed without user interference (that is, no code is required), but the unboxing of a value requires explicit conversion, that is, type conversion.

B. is Operator

The is operator is not used to indicate that an object is of a certain type, but to check whether the object is of a given type or whether it can be converted to a given type. If yes, true is returned.

<Operand> is <type>

  • If <type> is a class type, and <operand> is also of this type, or it inherits this type, or it can be encapsulated into this type, the result is true.
  • If <type> is an interface type, and <operand> is also the type, or it is the type that implements the interface, the result is true.
  • If <type> is a value type and <operand> is of this type, or it can be split into this type, the result is true.

(2) Value Comparison

A. Operator Overloading

To overload operators in a class, you must add operators to the class (using the operator keyword and operator itself) and must be static.

B. The IComparable and IComparer interfaces are widely used in collection classes.

  • IComparable is implemented in the class of the object to be compared. You can compare this object with another object.
  • IComparer is implemented in a separate class and can compare any two objects

Generally, IComparable is used to provide the default comparison code of the class and non-default comparison code for other classes. IComparable provides the CompareTo () method, which accepts an object. IComparer also provides a Compare () method.

Finally ,. net Framework provides the default implementation method of the IComparer interface on the class Comparer. The class Comparer is located in the System. in the Collections namespace, you can compare simple types and any types that support the IComparable interface with specific cultures.

3. Conversion

(1) overload conversion Operators

In the code, use the keywords implicit and explicit to specify the conversion

 1     public class ConvClass1 2     { 3         public int val; 4         public static implicit operator ConvClass2(ConvClass1 op1) 5         { 6             ConvClass2 returnVal = new ConvClass2(); 7             returnVal.val = op1.val; 8             return returnVal; 9         }10 11     }12     public class ConvClass213     {14         public double val;15         public static explicit operator ConvClass1(ConvClass2 op1)16         {17             ConvClass1 returnVal = new ConvClass1();18             returnVal.val = (int)(op1.val);19             return returnVal;20         }21     }

 

(2) as Operator

Use the following syntax to convert a type to a specified reference type.

<Operand> as <type>

  • The <operand> type is <type> type.
  • <Operand> can be implicitly converted to <type> type
  • <Operand> You can bind it to the <type> type.

If the expression cannot be converted from <operand> to <type>, the result of the expression is null.

Related Article

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.