C # generics

Source: Internet
Author: User

Generics overview

Generics are a special mechanism provided by the CLR that allows us to write code with a type placeholder and then provide a true type when an instance of the type is created. In many cases we can extract or refactor the behavior of a class, adding an abstraction layer that can be applied not only to hard-coded types, but also to other types, another form of code reuse. The advantages of generics are as follows:

    1. Regardless of the number of constructed types, there is only one implementation, effectively reducing the code bloat, while the code is more readable and easier to maintain.
    2. Generics provide a strongly-typed programming model that ensures that only the data types that members want are available. e.g new list<datetime> (). ADD ("string"); The best overloaded method match for ' System.collections.generic.list<system.datetime> will be error when compiling. ADD (System.DateTime) ' has some invalid arguments; Argument 1:cannot convert from ' string ' to ' System.DateTime ' because string cannot be converted to DateTime.
    3. Compile-time type checking can effectively reduce the chance of invalidcastexception exceptions occurring in the CLR.
    4. When generic class members use value types, they no longer cause a cast to object, they no longer need boxing or unboxing, reduce memory consumption, and improve performance.
Generic class

A generic type is still a type, and there are two steps in the process of using a non-generic class: Declaring the class, creating an instance of the class. But the generic type is not the actual type, but the template of the class, so we must first build the actual type and then create an instance of the actual type, in effect defining a new type object in the CLR, and the new type object is derived from the generic type from which type object. (e.g:mygeneric<t> derives from object so mygeneric<datetime>, mygeneric<string> is also derived from object).

generic class parameter naming guidelines: parameter naming should be as descriptive as possible, names should also be prefixed with T, eg:tkey,tvalue,tentity multiple types of parameters: generic types can use any number of type parameter e.g:action<t, T1,... Tn>

Parameter constraints: Constraints use WHERE clause where typeparam:constraint,constraint .... If there is a constructor constraint, it must be placed at the end .

    • Type name: Only this type of class or class inherited from it can be used as a parameter where t:classname
    • Interface constraints: Only this interface or the implementation of the interface type can be used as parameters, can have multiple interface constraints were t:interfacename,interfacename
    • Class constraint: Any reference type, including classes, arrays, delegates, interfaces, etc., can be used as a parameter where T:class
    • struct constraint: Any value type can be a parameter where t:struct
    • Constructor constraint: Any type with a non-parameter public constructor can be used as a parameter where t:new ()

Generic methods: Generic methods can be declared in generic class non-generic class structures and interfaces, where generic methods and generic classes have a type parameter list and an optional constraint list.

    Public classMyClass {Internal Static voidPrint<t>(t[] array) {foreach(varIteminchArray) {Console.Write (item. ToString ()+" ");        } Console.WriteLine (); }    }  Public classProgram {Private Static voidMain (string[] args) {            varIntarray =New int[] {1,2,3,4,5}; varStringarray =New string[] {"Hello"," World" }; varDoublearray =New Double[] {1.12,2.25,3.141592654};            Myclass.print (Intarray); Myclass.print<int>(Intarray);            Myclass.print (Stringarray); Myclass.print<string>(Stringarray);            Myclass.print (Doublearray); Myclass.print<Double>(Doublearray);        Console.readkey (); }    }
Generic Methods

Generic method overloading: C # defines the uniqueness of a function based on the method name, parameter type, number of arguments, parameter order, and does not include the return value type of the method, so we can look at the overloads of the generic method from these aspects.

The method groups that cannot be overloaded are:

    • public void mymethod<t> (T t) {}
    • public void Mymethod<u> (U u) {}
    • public void mymethod<t> (T-t) where t:basea{}
    • public void Mymethod<u> (U u) where u:baseb{}
    • Public T mymethod<t> (T t) {}
    • Public U mymethod<u> (U-u) {}

The groups of methods that can be overloaded are:

    • public void mymethod<t> (T t) {}
    • public void MyMethod (int i) {}
    • public void MyMethod (T T, u u) {}
    • public void MyMethod (U u, t t) {}
    • public void MyMethod (U u, T t,int a) {}

Override of a generic method: When overriding a virtual generic method, or when creating an explicit interface method implementation, the constraint is implicitly inherited and cannot be re-declared.

  Public classBaseClass { Public Virtual voidMymethod<t> (T t)whereT:New() {Console.WriteLine ("Base"); }    }   Public classSubclass:baseclass { Public Override voidMymethod<x> (x x)//where x:icomparable in the process of overriding, the constraints of abstract methods in abstract classes are inherited by default, so constraints cannot be specified directly{Console.WriteLine ("Sub"); Base. Mymethod<x>(x); }    }
overriding of generic methodsGeneric interface

Generic interfaces allow us to write parameters and interface member return types are interfaces to generic type parameters. The declaration of a generic interface is basically the same as a non-generic type interface declaration, except that the type parameter is added after the interface name is declared. When implementing a generic type interface, there must be no possible type argument combinations that produce two duplicate interfaces in a type. In the following example, if the second interface takes int as the type argument, the type will have two identical interfaces.

 interface  igeneric<t> {T Return    Value (T value);  class  mygeneric<u>:igeneric< int  >,igeneric<u> { public  int  returnvalue (int  Span style= "color: #000000;" > value) { throw  new  
   
     NotImplementedException ();             
    public  
     U returnvalue (U value) {  
    throw  
    new  
     NotImplementedException (); }    }
   
generic interface
    • Generic interfaces also provide excellent compile-time type security
    • The number of boxing times is much lower when working with value types
    • The same class can implement the same interface several times, as long as a different type parameter is used each time
Contravariance and covariance

Parameters for each generic type can be marked as a covariant or inverse variable. With this feature, one variable of a generic type can be converted to another variable, which greatly improves the compatibility of generic parameters.

    • Invariant: means that the generic type parameter cannot be changed.
    • Inverse variable: means that a generic type parameter can be changed from a base class to a derived class of that type. expressed in the In keyword. The generic type parameter of the inverse variable can only appear in the input position, such as the parameter of the method.
    • Covariance: means that a generic type parameter can be changed from a derived class to a base class, represented by an out keyword. The generic type parameter of the covariance can only appear in the output location, such as the return type of the method.

Dynamic-xia

Blog Address: Http://www.cnblogs.com/dynamic-xia

Disclaimer: This blog to study, research and sharing mainly, welcome reprint, but must be in the article page obvious location to give the original text connection.

C # generics

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.