Home  >  Article  >  Backend Development  >  Covariance and contravariance in C#

Covariance and contravariance in C#

WBOY
WBOYforward
2023-09-07 09:05:02802browse

C# 中的协变和逆变

To deal with classes efficiently, use the concepts of covariance and inverse variance.

Let's consider the following as our course. One is the base class for class two, and two is the base class for class three.

class One { 
}
class Two: One {
}
class Three : Two { 
}

Base classes can contain derived classes, but the reverse is not possible. Covariance allows you to pass a derived type where a base type is expected. Covariance can be used with arrays, interfaces, delegates, etc. in C#.

The contrast variance is for parameters. Allows methods with base class parameters to be assigned to delegates that require derived class parameters with contravariance.

The above is the detailed content of Covariance and contravariance in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete