Generic covariant and Inverter
Preface
Today, I am talking about a lot of content, but I can understand it almost. What is a bit vague is the concept of covariant and inverter. Below is a combination of materials I have read online.
Body
The original words on msdn:
Covariant: Refers to a type that can be used to derive a smaller (uncertain) degree than the original specified derivative type.
Invert: a type that can be used to derive a larger (more specific) degree than a derived type of the original type.
The easy-to-understand concept is:
Covariant: The subclass is converted to the parent class. The out keyword is used to return the type.
Invert: the conversion process from the parent class to the subclass. It is used by the in keyword for the method parameter type.
Example of covariant:
1 public class Person {} 2 3 public class Student: Person {} 4 5 public delegate T MyDelegate <out T> (); 6 class Program 7 {8 static void Main (string [] args) 9 {10 MyDelegate <Student> student = () => new Student (); 11 MyDelegate <Person> person = student; 12 13} 14}View Code
If the out keyword is removed here, an error that cannot be implicitly converted will be reported.
Example of inverter:
1 public class Person {} 2 3 public class Student: Person {} 4 5 public interface IFly <in T >{} 6 7 public class FlyImp <T>: IFly <T >{} 8 public delegate T MyDelegate <T> (T t); 9 class Program10 {11 static void Main (string [] args) 12 {13 14 IFly <Person> peson = new FlyImp <Person> (); 15 IFly <Student> student = peson; 16} 17}View Code
If IFly <in T> is removed, the implicit conversion error is also reported.
Wow, that's amazing!
Here we finally understand the meaning of in and out in the two delegates provided by ms: Action <in> and Func <out>.
Summary
After a simple understanding, with the help of covariant and inverter, code writing can be more flexible in the future. Of course, this is nonsense. Although it is simple, it still wastes a lot of time in coding, I also found my own low-handed problems. I have to practice more in the future.