« Variance » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Aucun résumé des modifications
Aucun résumé des modifications
Ligne 9 : Ligne 9 :


= Assignment compatibility =
= Assignment compatibility =
Allow an object of a more derived type (child class, ex: string) to be assigned to an object of a less derived type (parent class, ex: object).
<kode lang='cs'>
<kode lang='cs'>
string s = "test";
string s = "test";
object o = s;
</kode>


// An object of a more derived type is assigned to an object of a less derived type.
= Covariance =
object o = s;
Allow a generic object of child class type (ex: string) to be assigned to a generic object of parent class type (ex: object).
{{info | It works only with covariant interface}}
<kode lang='cs'>
var strings = new List<string>();
List<object> objects = strings;  // Cannot convert type List<string> to List<object> because there is no covariance with List<T>
IList<object> objects = strings;  // Cannot implicitly convert type List<string> to IList<object>. An explicit conversion exists
 
IEnumerable<object> objects = strings; // There is covariance with IEnumerable<T>
 
var objects = (IList<object>)strings; // There is covariance with IList<T>
</kode>
</kode>

Version du 26 mars 2024 à 14:51

Links

Description

Covariance enable implicit reference conversion for array types, delegate types, and generic type arguments.
Covariance preserves assignment compatibility and contravariance reverses it.

Assignment compatibility

Allow an object of a more derived type (child class, ex: string) to be assigned to an object of a less derived type (parent class, ex: object).

Cs.svg
string s = "test";
object o = s;

Covariance

Allow a generic object of child class type (ex: string) to be assigned to a generic object of parent class type (ex: object).

It works only with covariant interface
Cs.svg
var strings = new List<string>();
List<object> objects = strings;   // Cannot convert type List<string> to List<object> because there is no covariance with List<T>
IList<object> objects = strings;  // Cannot implicitly convert type List<string> to IList<object>. An explicit conversion exists

IEnumerable<object> objects = strings; // There is covariance with IEnumerable<T>

var objects = (IList<object>)strings; // There is covariance with IList<T>