C # Generic-generic class

Source: Internet
Author: User

Why do you need generics:

A new feature of CLR 2.0 is generics. In. CLR 1.0, to create a flexible class or method, but the class or method does not know what class to use during compilation, it must be based on the Object class. The Object class does not have type security during compilation, so forced type conversion is required. In addition, using the Object class for the value type will result in performance loss.

 

Performance

1. One of the main advantages of generics is performance. Avoid packing and unpacking.

For example, in the ArrayList Method Add (Value), the value can be added as long as it inherits the object, but it needs to be: boxed; In foreach mode, it needs to be split.

(Converting from a value type to a reference type is called packing, and vice versa)

 

Ii. type security

For example, in List <T>, if generic type T is defined as the allowed int type, the value in the Add (value) method only supports the int value type.

 

Third, reuse of binary code (generic classes can be defined once and instantiated with many different types)

Example: List <int> list = new List <int> (); list. Add (1 );

List <string> stringList = new List <string> (); stringList. Add ("string ");

Generic types can be defined in one language and used in another. NET language.

 

 

Case:

DocumentManager

/** Note: examples of using generic document manager ** Note: * The default keyword can have multiple meanings based on the context. The switch statement uses default to define the default condition. In generics, the root * indicates whether the generic data type is a reference type or a value type. The default keyword is used to initialize the generic data type to null or 0. ** Created: 2012-04-26 */using System; using System. collections. generic; using System. text; using System. collections; namespace DocumentManager {// class constraints are specified. type T must execute the interface IDocument public class DocumentManager <T> where T: IDocument {private readonly Queue <T> documentQueue = new Queue <T> (); // <summary> // AddDocument () method to add a document to the // queue. If the queue is not empty, the IsDocumentAvailable read-only attribute returns true // </summary> // <param name = "doc"> </param> public void AddDocument (T doc) {lock (this) {documentQueue. enqueue (doc); }}/// <summary> // a value in the queue returns True, otherwise False /// </summary> public bool IsDocumentAvailable {get {return documentQueue. count> 0 ;}} /// <summary> /// specify the default value for type T. /// </summary> /// <returns> </returns> public T GetDocument () {T doc = default (T); // generic default value: use the default keyword lock (this) {doc = documentQueue. dequeue () ;}return doc ;}/// <summary> /// display all documents /// </summary> public void DisplayAllDocument () {foreach (T doc in documentQueue) {Console. writeLine (IDocument) doc ). title );}}}}

Document

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace DocumentManager{    public class Document : IDocument    {        public Document()         {        }        public string Title { get; set; }        public string Content { get; set; }        public Document(string title, string content)        {            this.Title = title;            this.Content = content;        }    }}

TDocument

namespace DocumentManager{    public class TDocument : IDocument    {        public TDocument()         {        }        public string Title { get; set; }        public string Content { get; set; }        public TDocument(string title, string content)        {            this.Title = title;            this.Content = content;        }    }}

 

/** If a generic class needs to call a method on the generic type, you must add the constraint **/using System; using System. collections. generic; using System. linq; using System. text; namespace DocumentManager {public interface IDocument {string Title {get; set ;}string Content {get; set ;}}}

 

Program

 class Program    {        static void Main(string[] args)        {            //DocumentManager<TDocument> tm = new DocumentManager<TDocument>();            //tm.AddDocument(new TDocument("Title TDocument","Content TDocument"));            //tm.DisplayAllDocument();            DocumentManager<Document> dm = new DocumentManager<Document>();            dm.AddDocument(new Document("Title A", "Sample A"));             dm.DisplayAllDocument();            dm.AddDocument(new Document("Title B", "Sample B"));            dm.DisplayAllDocument();            if (dm.IsDocumentAvailable)            {                Document d = dm.GetDocument();                Console.WriteLine(d.Content);            }        }    }

 

 

Result: It is recommended that you calculate the value by yourself ......

 

 

 

 

(Is it different from what you want? Then take a good look at the code)

 

 

 

 

 

 

 

Note:

 
The default keyword can have multiple meanings based on the context. The switch statement uses default to define the default condition. In generics, the root
Whether the generic type is a reference type or a value type. The default keyword is used to initialize the generic type to null or 0.

 

If a generic class needs to call a method on a generic type, you must add constraints. Format: where + constraint type

 

About bundle Description
Where T: struct Use structure constraints. The type T must be a value type.
Where T: class Class constraints are specified. type T must be a reference type.
Where T: IFoo The specified type T must execute the interface IFoo
Where T: Foo The specified type T must be derived from the base class Foo.
Where T: new () This is a constructor constraint. A default constructor must exist for the specified type T.
Where T: U

This constraint can also be specified. Type T1 is derived from generic Type T2. This constraint is also known as bare type approx.
Bundle

In the where clause, you can only define the base class, interface, and default constructor.

 

 

Static Member
Special attention is required for static members of generic classes. Static members of a generic class can only be shared in one instance of the class.
// Pay special attention to the static members of generic classes. Static members of a generic class can only be shared in one instance of the class. // because StaticDemo is used for a string type and an int type, there are two sets of static fields: staticDemo <int>. x = 1; StaticDemo <string>. x = 11; StaticDemo <char>. x = 111; Console. writeLine (StaticDemo <string>. x); Console. writeLine (StaticDemo <int>. x );
    public class StaticDemo<T>    {        public static int x;    }

 

 

 

 

 

 

 

Introduced from C # Advanced Programming

 

 

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.