Contra and Co dispersion - CLR via C #

In CLR through C # the third edition there is an example which, in my opinion, does not make sense:

Invariant means that this general type parameter cannot be changed. I have shown only the invariant general type of parameters in this chapter. P

Contravariant The value that the general type parameter can vary from class to class derived from it. In C # you specify a contravariant general type of parameters with by keyword .

Type contravariant parameters can appear only in input positions such as the argument of methods. N Covariant The value that the general type argument can vary from class to one of its base classes. In C #, you specify the covariance generic type parameters with the keyword out . Type covariant parameters can only appear in output positions, such as the type of the return method.

Further, the author gives the following example:

public delegate TResult Func<in T, out TResult>(T arg);

Here is a general parameter of type T marked with keywords, which makes it contravariant; and the generic type parameter TResult is marked out, making it covariant

This is where I ran into the problem on the next page (292), then he continues to talk about the opposite when using the interface.

, , , , . , . > type:

public interface IEnumerator<out T> : IEnumerator {
Boolean MoveNext();
T Current { get; }
}

T , , > :

// This method accepts an IEnumerable of any reference type
Int32 Count(IEnumerable<Object> collection) { ... }
...
// The call below passes an IEnumerable<String> to Count
Int32 c = Count(new[] { "Grant" });

out (IEnumerator<out T>), . - . , ? - Oreilly , .

+5
2

out= in= .

- , .

+20

. . .

O'Reilly .

+8

All Articles