Generics of C #

Source: Internet
Author: User

Default value

Now let's create a new instance, in which a generic class test<t> is defined, and a Getmodel method in the generic class returns a T-type

 Public class Test<t>    {        public  T getmodle ()        {            default(t);             return model;        }    }
default (T);

Assign NULL to a reference type by using the default keyword, assigning 0 to a value type

Constraints

The conditions for some generic constraints are given below

Inherited

1. A generic type can implement a generic interface, or it can derive from a generic class

2. A derived class can be a generic class or a non-generic class

To define an abstract generic base class

 Public Abstract class Calc<t>    {        publicabstract  t Add (t X, t y);          Public Abstract T Sub (t X, t y);    }

Non-generic classes can be defined in derived classes

class intcalc:calc<int>    {        publicoverrideint Add (int  int  y)        {            return x + y;        }          Public Override int Sub (intint  y)        {            return x- y;        }    }
Covariance and Contravariance

Feel covariant like polymorphism

First, we define a simple class

 public  class   people { public  int  Id {get ; set         ;}  public  string  Name {get ; set         ;}  public  int  Age {get ; set     ;} }
class Chinese:people    {        publicstringgetset;}    }

New Chinese ();

In this way, we simply inherit and implement the implicit conversion of the type.

Chinese C = (Chinese) p;

This is a cast of type

In the generic interface, can we also do the following assumptions, first we define a generic interface

Interface Imyinterface<t>{}

If both implicit and cast of the above types exist, the following code can be compiled through the

imyinterface<people> p=New imyinterface<chinese>() imyinterface<Chinese> c= ( imyinterface<chinese>) p;

But there is no such definition in the generic interface before. net4.0 (c#4.0), so Microsoft has the concept of covariance and contravariance after c#4.0.

Covariance: Changes in generic interfaces from subclasses to parent classes

Inversion: The change of generic interface parent class to subclass

Condition: The generic parameter T is decorated by adding int and out to the declaration of the generic interface

Considerations for Covariance and contravariance:

1. Covariance and contravariance are not supported for type parameters of class or generic methods, only interfaces and delegates support covariance and contravariance (such as Func<out tresult>,action<in t>).

2. Covariance and contravariance are only applicable to reference types, and value types do not support covariance and contravariance (because there is a reference conversion for variability, whereas value type variables store the object itself, not the object's reference), so list<int> cannot be converted to ienumerable< Object>.

3. The type parameter must be marked with in or out.

Generic methods

Generic methods can be defined in non-generic classes

An example of the use of a simple generic method

Static void Swap<t> (refref  T y) {            t temp;             = x;             = y;             = temp;        }

int 4 ;     int 5 ;    Swap<int> (ref X,ref  y);    Console.WriteLine (string. Format ("x Value {0},y value {1}", x, y));

In the definition of a simple example

 Public Static decimal where Taccount:iaccount       {           decimal0;            foreach inch source) {               + = a.balance           ;           } return sum;       }

Overloading of generic methods

 Public void foo<t>(t obj)       {           Console.WriteLine ("foo<t> (t obj), obj type:{0}"  , obj. GetType (). Name);       }         Public void Foo (int  x)       {           Console.WriteLine ("foo (int x)" ) );       }

During compilation, if you pass an int type, you select a method with an int parameter, and for other types, the compiler chooses a different method

Generics of C #

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.