Generalization of the inverse and covariance of generics C # generic Inverse covariant
- The concept of change
- Covariant (foo< parent class > = foo< subclass >)
- Contravariance (foo< Subclass > = foo< parent >)
- The interaction between contravariance and covariance
The concept of change
- //Parent class = Subclass
- string str = "string";
- object obj = str; //Changed
Covariant (foo< parent class > = foo< subclass >)
- //Generic delegate:
- public delegate T myfunca<t> (); //does not support contravariance and covariance
- Public Delegate T myfuncb< out t> (); //Support co-change
-
- myfunca<Object> funcaobject = null;
- myfunca<string> funcastring = null;
- myfuncb<Object> funcbobject = null;
- myfuncb<string> funcbstring = null;
-
- Funcaobject = funcastring; //Compile failed, Myfunca does not support contravariance and covariance
- Funcbobject = funcbstring; //changed, covariant
Contravariance (foo< Subclass > = foo< parent >)
- public delegate void myactiona<t > (T param); //does not support contravariance and covariance
- Public Delegate void myactionb< in t> (T param); //Support inverter
-
- myactiona<Object> actionaobject = null;
- myactiona<string> actionastring = null;
- myactionb<Object> actionbobject = null;
- myactionb<string> actionbstring = null;
-
- actionastring = Actionaobject; //myactiona does not support contravariance and covariance, compilation fails
- actionbstring = Actionbobject; //changed, invert
-
If the In keyword is added as a generic modifier on a generic parameter, then that generic parameter can only be used as the input parameter of the method, or as a parameter of a write-only property, not as a method return value, etc., in short, can only be "in", not out. The Out keyword instead.
The interaction between contravariance and covariance
- Public Interface IBar< in T> {}
- //should be in
- Public Interface IFoo< in T>
- {
- void Test(ibar<t> bar);
- }
- //or out
- Public Interface IFoo< out T>
- {
- void Test(ibar<t> bar);
- }
IFoo with covariant capability requires that its generic parameters (IBar) have the inverse capability
Summary of the inverse and covariance of generics