. NET generic 03, generic type conversion, covariant and inverter,. net03

Source: Internet
Author: User

. NET generic 03, generic type conversion, covariant and inverter,. net03

The emergence of Convariant and Contravariant makes it possible to implicitly convert arrays, delegates, and generics. A subclass is converted to a base class, which is called a covariant. A base class is converted to a subclass, which is called an inverter .. Since NET4.0, it has supported covariant and inverter for generic interfaces.

 

Generic covariant

If the subclass generic type is implicitly converted to the base class generic type, use generic covariant.

 

There are two base classes and derived classes.

Public class Animal {public virtual void Write () {Console. writeLine ("I Am a base class") ;}} public class Dog: Animal {public override void Write () {Console. writeLine ("I Am a puppy ");}}

 

To implicitly convert a derived class Dog to a base class Animal, define a generic interface that supports covariant.

// Public interface ifacloud <out T> {T Create ();}

 

Then implement this interface.

public class Factory<T> : IFactory<T>    {        public T Create()        {            return (T)Activator.CreateInstance<T>();        }    }

 

Client call.

Class Program {static void Main (string [] args) {ifacloud <Dog> dogFactory = new Factory <Dog> (); ifacloud <Animal> animalFactory = dogFactory; // covariant Animal animal = animalFactory. create (); animal. write (); Console. readKey ();}}

 

Running output: I am a puppy

 

As shown above, we can see:
● After the covariant, the methods of the parent class are completely replaced by child classes, and the original methods of the parent class no longer exist.
● Out keywords in generic interfaces are essential


 

Generic inverters

An interface for notifications.

public interface INotification    {        string Message { get; }    }

 

Abstract Implementation of the notification interface.

public abstract class Notification : INotification    {        public abstract string Message { get; }    }

 

The specific implementation of the notification abstract class.

Public class MailNotification: Notification {public override string Message {get {return "You have an email ~~ ";}}}

 

Next, you need to publish the notification information. You need an interface INotifier that publishes the notification. This interface depends on INotification, roughly INotifier <INotification>, and the notification is finally displayed, we want INotifier <MailNotification> and INotifier <INotification> to be converted to INotifier <MailNotification>. This is an inverter and requires the keyword in.

public interface INotifier<in TNotification> where TNotification : INotification    {        void Notify(TNotification notification);    }

 

Implement INotifier.

public class Notifier<TNotification> : INotifier<TNotification> where TNotification : INotification    {        public void Notify(TNotification notification)        {            Console.WriteLine(notification.Message);        }    }

 

Client call.

Class Program {static void Main (string [] args) {INotifier <INotification> notifier = new Notifier <INotification> (); INotifier <MailNotification> mailNotifier = notifier; // inverter. Y (new MailNotification (); Console. readKey ();}}

Run the output: You have an email ~~

 

As shown above, we can see:
● The parameter type of the INotifier method Notify () is INotification. After the inverter, The INotification type parameter is implicitly converted to the implementation class mailpolicicaiton.
● In keywords in generic interfaces are essential

 

References:
NET (version 2nd), Author: Wang Tao.

 

". NET generic" series include:

. NET generic 01. Why does it need generic and basic syntax. NET generic 02, generic use. NET generic 03, generic type conversion, covariant, and inverter. NET generic 04, use Lazy <T> to implement delayed Loading
What is the co-Variation and inverter in the NET generic model?

Current. NET languages such as VB and C # do not support generic covariance and contravariance ). Although many people in Microsoft are talking about it, it is unlikely to happen in the near future. It takes a long time to fully introduce the covariant and inverter. Based on this, please refer to Eric Lippert's series of articles on covariant and inverter in C. Lucian Wischik introduces the following syntax to add wildcard support for covariant and inverter in VB.

Type parameters can be modified by the keyword "In" and "Out. The "In" type can only be used as a method parameter. Similarly, the "Out" type can only be used as the return type of the method.

An example Of the Out type is IEnumerable (Of T ). If a function accepts an IEnumerable (Of Animal) type parameter, we can pass it an IEnumerable (of Bird ). An incorrect example of the In type is sequence. See Interface IWriter (Of T) Write (value As T) in detail)

If you pass an IWriter (Of Bird) to a function that accepts the Writer (Of Animal) type parameters, Of course not. This method can pass any subclass of Animal to IWriter. write, but it only accepts Birds. if annotations are used, the Interface looks like the following: Interface IEnumerable (Of Out T) Interface IWriter (Of In T)

This is written for VB and can be used in C.
Interface IEnumerableinterface IWriter unfortunately, this syntax cannot be directly applied in most common scenarios. For example, if IList (Of T) is passed to a method written to the set, T should be In type. But when it is passed to a method to read from the set, T should be of the Out type. Perhaps we should create a base class for IList, which will distinguish the methods that accept T from the return T.

Back to the past, both C # and VB support array covariant (out/IEnumerable), even if the inverter causes a running error (in/IWriter ). This is intended to make C # more compatible with Java. Most people think this is a bad design, but it cannot be changed now.

What is the generic covariant Inverter in net40?

It is a combination, such as string [] a, which is also assigned a value. When we forcibly convert (int []) a, the elements in it are also converted to int.

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.