General learning notes for C # advanced programming (version 6) (I): general advantages and features,

Source: Internet
Author: User

General learning notes for C # advanced programming (version 6) (1): general advantages and features (reproduced ),

Source: http://www.cnblogs.com/xun126/archive/2011/01/13/1933838.html

Generic is a new feature of CLR 2.0. In CLR 1.0, you need to create a flexible class or method, but this class or method does not know what class to use during compilation, object Class. The Object does not have type security during compilation. Therefore, forced type conversion must be performed. At the same time, performance loss may occur when you use the Object class for the value type. Generic classes use generic types, and can replace generic types with specific types as needed. This ensures type security: if a type does not support generic classes, the compiler reports an error.

I. generics have the following advantages:

1) Performance

Non-generic collection classes are used for value types. When you convert a value type to a reference type or convert a reference type to a value type, you need to bind and unbox the value type. The packing and unpacking operations are easy to implement, but the performance loss is high. If the generic type is used, the packing and unpacking operations can be avoided.

1 ArrayList list = new ArrayList (); 2 list. add (20); // boxed. The list stores object-type elements. The value type must be converted to the reference type. 3 int I = (int) list [0]; // unpack. The type of list [0] is object. To assign a value, you must convert the reference type to the value type.

If you change to generic programming, there will be no performance loss for packing and unpacking.

1 List <T> list = new List <int> (); 2 list. add (20); // because int is specified for instantiation, it is not necessary to pack 3 int I = list [0]; // Similarly, you do not need to unpack during access.

  

2) type security

Like the ArrayList class, if you use an object, you can add any type to this set.

If you use non-generic programming, the following code may cause exceptions in some cases.

1 ArrayList list = new ArrayList (); 2 list. add (20); 3 list. add ("string"); 4 list. add (new MyClass (); 5 6 foreach (int I in list) 7 {8 Console. writeLine (I); // there is an exception here, because not all elements in the set can be converted to int 9}

If generic programming is used, this exception can be avoided and the compiler checks for errors.

1 List <int> list = new List <int> (); 2 list. add (20); 3 lsit. add ("string"); // an error is reported during compilation. Only values of the integer type can be added to the four lists in the set. add (new MyClass (); // same as above

  

3) binary code reuse

Generics can be defined once and instantiated with many different types. You do not need to access the source code like the C ++ template. Generics can be defined in one language and used in another. NET language.

 

4) code Extension

Because the definition of a generic class is placed in the Assembly, instantiating a generic class with a certain type will not replicate these classes in the IL code. However, when the JIT compiler translates generic classes into internal code, a new class is created for each value type. The reference type shares all the implementation code of the same internal class. This is because the reference type only requires a 4-byte memory unit (32-bit system) in the instantiated generic class and can reference a reference type. The value type is included in the memory of the instantiated generic class. Each value type has different requirements on memory, so a new class should be instantiated for each value type.

 

Ii. Features of generic classes

1) Default Value

When initializing type T, be sure not to assign null to the generic type. Because the generic type can also be instantiated as the value type, and null can only be used to reference the type. To solve this problem, you can use the default keyword. Use the default keyword to assign null to the reference type and 0 to the value type.

1 public T GetDoucumet () 2 {3 T doc = default (T); 4 lock (this) 5 {6 doc = documentQueue. dequeue (); 7} 8 return doc; 9}

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

 

2) Constraints

If a generic class needs to call a method on a generic type, you must add constraints.

1 public class DocumentManager <T> 2 {3 private readonly Queue <T> documentQueue = new Queue <T> (); 4 5 public void AddDocument (T doc) 6 {7 lock (this) 8 {9 documentQueue. enqueue (doc); 10} 11} 12 13 public bool IsDocumentAvailable 14 {15 get 16 {17 return documentQueue. count> 0; 18} 19} 20} 21 22 public interface IDocument 23 {24 string Title {get; set;} 25 string Content {get; set ;} 26} 27 28 public class Document: IDocument 29 {30 public Document () 31 {32} 33 34 public Document (string title, string content) 35 {36 this. title = title; 37 this. content = content; 38} 39 40 public string Title {get; set;} 41 public string Content {get; set;} 42}

If you use the DocumentManager <T> class to display documents, you can forcibly convert type T to the IDocument interface.

1 public void DisplayAllDocument () 2 {3 foreach (T doc in documentQueue) 4 {5 Console. WriteLine (IDocument) doc). Title); 6} 7}

If type T does not execute the IDocument interface, this type conversion generates an exception. Therefore, you need to define a constraint for the DocumentManager <T> class: T must execute the IDocument interface, to specify this requirement in the generic type name, change T to TDocument. The wherer clause specifies the requirements for executing the IDocument interface.

1 public class DocumentManager <TDocument> where TDocument: IDocument 2 {3... 4}

In this way, the foreach statement can contain the Title attribute of type T.

1 public void DisplayAllDocument () 2 {3 foreach (TDocument doc in documentQueue) 4 {5 Console. WriteLine (doc. Title); 6} 7}

In the Main () method, the DocumentManager <T> class is instantiated using the Document type, while the Document type executes the required IDocument interface.

1 static void Main () 2 {3 DocumentManager <Document> dm = new DocumentManager <Document> (); 4 dm. addDocument (new Document ("Title A", "A"); 5 dm. addDocument (new Document ("Title B", "B"); 6 dm. displayAllDocument ();

 

In addition, there are several constraints for generics. As follows:

1) where T: struct uses structural constraints. Type T must be a value type

2) where T: class constraints are specified. The type T must be a reference type.

3) where T: IFoo specifies the type T, and the interface IFoo must be executed.

4) where T: Foo specifies that the type T must be derived from the base class Foo.

5) where T: new () constructor constraint. A default constructor is required for the specified type T.

6) where T: U Type T1 is derived from generic Type T2. This constraint is also a bare type constraint.

Note: You can also combine multiple constraints using generic types. Where T: IFoo, new () Constraint and MyClass <T> Declaration are specified. The type T must execute the IFoo interface and have a default constructor.

1 public class MyClass <T> where t: IFoo, new () 2 {3... 4}

  

3) Inheritance

A generic type can execute a generic interface or be derived from a class. Generic classes can be derived from generic base classes:

1 public class Base <T> 2 {3 4} 5 6 public class Derived <T>: Base <T> 7 {8 9}

The generic type of the interface must be repeated, or the type of the base class must be specified.

1 public class Base <T> 2 {3 4} 5 6 public class Derived <T>: Base <string> 7 {8 9}

Therefore, a derived class can be a generic class or a non-generic class. For example, you can define an abstract generic base class, which is implemented with a specific type in the derived class.

1 public abstract class Calc <T> 2 {3 public abstract T Add (T x, T y); 4 public abstract T Sub (T x, T y ); 5} 6 7 public class SimpleCalc: Calc <int> 8 {9 public override int Add (int x, int y) 10 {11 return x + y; 12} 13 14 public override int Sub (int x, int y) 15 {16 return x-y; 17} 18}

 

4) Static members

 

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.

1 public class StaticDemo <T> 2 {3 public static int x; 4}

The StaticDemo <T> class is used for a string type and an int type, so there are two sets of static fields:

1 StaticDemo <string>. x = 4; 2 StaticDemo <int>. x = 5; 3 Console. WrileLine (StaticDemo <string>. x); // output 4

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.