Generics--Collection interface

Source: Internet
Author: User
Tags foreach

9.4 Collection Interface

The. NET Framework provides two sets of standard interfaces for enumeration and contrast of collections: traditional (not type-safe) and new generic type-safe collections. This book focuses on the new, type-safe collection interface, because it is superior.

You can declare some icollection of the specified type to replace the actual type (such as int or string) for the generic type (<T>) in the interface declaration.

C + + programmers need to be aware that the templates in C # generics and C + + are similar in syntax and usage. However, because generics extend for their specified types at run time, the JIT compiler can share a piece of code for their different instances, which makes the problem of code bloat that is likely to occur when using C + + templates decreases significantly.

The key generic collection interfaces are listed in table 9-2:

For backward compatibility, C # also provides nongeneric interfaces (e.g., ICollection, IEnumerator), but they aren ' t consi dered here because they are obsolescent.

For backward compatibility, C # also provides non-generic interfaces (such as Iconnection,ienumerator), but they are not listed here because they are slowly discarded.

Table 9-2 Collection Interfaces

/tr> tr>
interface use
ICOLLECTION<T>
IENUMERATOR<T>

Ienumerable<t>
ICOLLECTION<T>
icomparer <t>

Icomparable<t>
ILIST<T>
IDICTIONARY<K,V> use in a set based on a key/value, such as dictionary
9.4.1 Ienumerable&lt;t&gt; Interface

You can implement the Ienumerable<t> interface to enable the Listboxtest to support the foreach statement (see Example 9-11). IEnumerable has only one method: GetEnumerator (), which works by returning a class that implements the Ienumerator<t> interface. The C # language uses a new keyword yield to provide special help for creating enumerators (enumerator).

Example 9-11 an enumerable class that creates a ListBox

using System;


using System.Collections; Translator Note: The original sentence is not, you must add


using System.Collections.Generic;


using System.Text;


namespace Enumerable


{


public class listboxtest:ienumerable&lt;string&gt;


  {


private string[] strings;


private int ctr = 0;

The
//enumerable class can return an enumerator


public ienumerator&lt;string&gt; GetEnumerator ()


    {


foreach (string s in strings)


yield return s;


    }


/* Translator Note: Generic IEnumerable is defined as


*public interface ienumerable&lt;t&gt;: IEnumerable


* That is, the implementation of the generic version IEnumerable must also be implemented simultaneously


* Non-generic version of the IEnumerable interface, the original code does not have this content, the following three lines


* Code is added so that the code can be copied and run directly/


IEnumerator Ienumerable.getenumerator ()


    {


return GetEnumerator ();


    }


//Using an array of strings to initialize the listbox


public listboxtest (params string[] initialstrings)


{


//Allocate space for strings


strings = new String[8];


//copy of an array of strings passed in from the construction method


foreach (string s in initialstrings)


      {


strings[ctr++] = s;


      }


    }


//Add a string at the end of the listbox


public void Add (string thestring)


    {


strings[ctr] = thestring;


ctr++;


    }


//Allow access like an array, is actually an indexer, if you do not understand the indexer please visit:


//http://www.enet.com.cn/eschool/video/c/20.shtml


public String This[int index]


    {


Get


      {


if (Index &lt; 0 | | | Index &gt;= strings. Length)


        {


//Handling Error index


//Translator Note: The original text does not add code here, I added an exception down


throw new ArgumentOutOfRangeException ("index", "Index out of range");


        }


return Strings[index];


      }


Set


      {


Strings[index] = value;


      }


    }


//Get the number of owning strings


public int getnumeneries ()


    {


return CTR;


    }


  }


public class Tester


{


static void Main ()


    {


//Create a new ListBox and initialize the


listboxtest LBT = new Listboxtest ("Hello", "World");


//Add some strings


LBT. ADD ("who");


LBT. ADD ("is");


LBT. ADD ("John");


LBT. ADD ("Galt");


//Access Test


string subst = "universe";


lbt[1] = subst;


//List all strings


foreach (string s in LBT)


      {


Console.WriteLine ("Value: {0}", s);


      }


    }


  }


}

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.