Covariance and Contravariance in c#4.0

Source: Internet
Author: User

Original address
Talk about. The covariance and contravariance in net

On covariance and contravariance, we should start with object-oriented inheritance. An inheritance relationship is a relationship between a child class and a parent class, and a subclass inherits from the parent class, so an instance of the subclass is the instance of the parent class. For example, animal is the parent class, and dog is a subclass inherited from animal; If the type of an object is dog, then he must be animal.

covariant inversion is the transformation of a delegate or generic interface between different parameter types or return value types using an inheritance relationship. I admit that this sentence is very round, if you also feel like a detour to look down.

If a method is to accept the dog parameter, then another method that accepts the animal parameter must also accept the parameter of the method, which is the animal shift to the dog direction is the inverse. If a method requires a return value of animal, then the method of returning to dog must be able to meet its return value requirement, which is the change in the direction of the dog to animal is covariant.

The transition from a subclass to a parent class is covariant covariance used to return a value type with the Out keyword
The transition from the parent class to the subclass direction is the inverse contravariant used for the parameter type of the method in the keyword

The covariance in covariant inversion is relative to the inheritance chain direction of the inheritance relation.

A Covariance of arrays:

    Animal[] animalArray = new Dog[]{};  

The above line of code is legal, the declared array data type is animal, while the actual assignment is given to the dog array, each dog object can be safely converted to animal. The change of the dog-to-animal method is a covariant, which shifts upward along the succession chain.

two. Covariance and contravariance in delegates
1. Covariance in a delegate

//委托定义的返回值是Animal类型是父类public delegate Animal GetAnimal();//委托方法实现中的返回值是Dog,是子类static Dog GetDog(){return new Dog();}//GetDog的返回值是Dog, Dog是Animal的子类;返回一个Dog肯定就相当于返回了一个Animal;所以下面对委托的赋值是有效的GetAnimal getMethod = GetDog;  

2. Contravariance in a delegate

//委托中的定义参数类型是Dogpublic delegate void FeedDog(Dog target);//实际方法中的参数类型是Animalstatic void FeedAnimal(Animal target){}// FeedAnimal是FeedDog委托的有效方法,因为委托接受的参数类型是Dog;而FeedAnimal接受的参数是animal,Dog是可以隐式转变成Animal的,所以委托可以安全的的做类型转换,正确的执行委托方法;FeedDog feedDogMethod = FeedAnimal;  

When defining a delegate, the parameter is a subclass, in fact the parameter of the delegate method is the broader parent class animal, is the parent class to the subclass direction change, is the inversion.

three. Covariance and contravariance of generic delegates:
1. Contravariance in Generic delegates
The following delegate declaration:

    public delegate void Feed<in T>(T target);  

The feed delegate accepts a generic type T, noting that there is an in keyword in the angle brackets of the generic, which is the function of telling the compiler that type T may have to be reversed when assigning a value to a delegate.

//先声明一个T为Animal的委托Feed<Animal> feedAnimalMethod = a=>Console.WriteLine(“Feed animal lambda”);//将T为Animal的委托赋值给T为Dog的委托变量,这是合法的,因为在定义泛型委托时有in关键字,如果把in关键字去掉,编译器会认为不合法Feed<Dog> feedDogMethod = feedAnimalMethod; 

2. Covariance in generic delegates

The following delegate declaration:

    public delegate T Find<out T>();  

The Find delegate returns an instance of a generic type T, with an out keyword in the angle brackets of the generic that indicates that the T type is likely to be covariant.

    //声明Find<Dog>委托Find<Dog> findDog = ()=>new Dog();//声明Find<Animal>委托,并将findDog赋值给findAnimal是合法的,类型T从Dog向Animal转变是协变Find<Animal> findAnimal = findDog; 

Four Covariance and contravariance in a generic interface:

Covariant contravariance in a generic interface is very similar to a generic delegate, except that the angle brackets of the generic definition are swapped for the definition of the interface.

1. Contravariance in a generic interface
The following interface definitions:

    public interface IFeedable<in T>{void Feed(T t);}  

An in keyword before the generic t of the interface to indicate that the generic interface might have to be contravariant

As the following generic type Feedimp, implementation of the above generic interface, it should be noted that the covariant and contravariant keyword In,out is not used in the generic class, the compiler does not allow

    public class FeedImp<T>:IFeedable<T>{    public void Feed(T t){ Console.WriteLine(“Feed Animal”); }} 

Consider an example of using an interface inversion:

    IFeedable<Dog> feedDog = new FeedImp<Animal>();  

The above code assigns the Feedimp type to the ifeedable variable; animal changes to the dog, so it's the inverse.

2. Covariance in generic interfaces
The following interfaces are defined:

    public interface IFinder<out T> {    T Find();}  

The generic interface's generic t was preceded by an out keyword to illustrate that this interface is likely to be covariant; The following generic interface implementation class.

public class Finder<T>:IFinder<T> where T:new(){    public T Find(){ return new T(); } } 

With covariance, the generic type of Ifinder is animal, but because of the Out keyword, I can assign the finder to it.

IFinder<Animal> finder = new Finder<Dog>();

The concept of covariance and contravariance is not easy to understand, and can be understood through actual code thinking. Is it really useful to wrap things around like this? The answer is yes, the code can be reused better through covariance and contravariance. Reuse is an eternal pursuit of software development.

Covariance and Contravariance in c#4.0

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.