c # - generics, covariant inverter

Generic brief:

You can use generic statement elements: classes, interfaces, methods, commissioned

Before Generic:
Generic object prior to use different types of packaging parameters disadvantages: poor performance, determining the type (secure) ... runtime
generic type is converted to an actual copy during compilation, the performance is good, it can also be used generic constraints constrain

Generic constraints:
constraints generic type must satisfy the constraints. After use generic constraints, like the way you can use generic types of constraints using variables

Kind of constraint:
WHERE T: // class reference type constraint
where T: new () // no argument constructor constraint, the constraint may be added to create this instance constructor with no arguments: T T = T new new ();
WHERE T : // class class or subclass specific constraint
where T: // specific interfaces or sub-interfaces constrained
where T: struct // value type constraint

 

Covariance inverter:

Covariance inverter only on the use of the interface or delegate

Personal understanding: Covariance inverter can make our code more flexible, help us to do a type conversion operation. Covariant turn is a subclass of the parent class; rotor inverter is the parent of the class.

Covariant (out): Returns the value of the modification, the generic return type can only appear in the members, do not pass parameters

Covariant case:

    public class Bird
    {
        public string ID { get; set; }
    }
    public class Sparrow : Bird
    {
        public string Name { get; set; }
    }

static void Main(string[] args)
        {
            Bird Bird = new new Sparrow (); // correct, a sparrow is a bird 
            List <Bird> birdList = null ;
             // birdList = new new List <Sparrow> (); // error, a group of sparrows and a flock of birds did not inherit relationship
             // only by the following two methods 
            birdList = new new List <Sparrow> () the Select (S => (Bird) S) .ToList ();. // mode. 1 
            birdList = new new List <Sparrow> (). Cast <Bird> () ToList ();. // mode 2
             // above two methods to write too much trouble, so have covariance, covariant is to solve this problem 
// Why is this not being given the following IEnumerable <Bird> = iBirdList new newList <Sparrow> (); // because IEnumerable <out T> Interface supports covariant using covariant out keyword }

In contrast with the covariant inverter, converting the subclass is the parent class, in use keyword. Generic type can only appear on the passed parameter

Inverter Case:

    public interface ICustomerEnumerable<in T>
    { 
    
    }
    public class CustomerEnumerable<T> : ICustomerEnumerable<T>
   { 

   }

  static void Main(string[] args)
   {
        //in 逆变
       ICustomerEnumerable<Sparrow> sparrowList = new CustomerEnumerable<Bird>();
   }

 

 

 

Guess you like

Origin www.cnblogs.com/fanfan-90/p/11963741.html