c# covariant generic parameter

前端 未结 3 500
挽巷
挽巷 2020-12-05 00:04

I\'m trying to understand this but I didn\'t get any appropriate results from searching.

In c# 4, I can do

    public interface IFoo
            


        
3条回答
  •  广开言路
    2020-12-05 01:10

    If we're talking about generic variance:

    Covariance is all about values being returned from an operation back to the caller.

    Contravariance It’s opposite and it's about values being passed into by the caller:

    From what I know if a type parameter is only used for output, you can use out. However if the type is only used for input, you can use in. It's the convenience because the compiler cannot be sure if you can remember which form is called covariance and which is called contravariance. If you don't declare them explicitly once the type has been declared, the relevant types of conversion are available implicitly.

    There is no variance (either covariance or contravariance) in classes because even if you have a class that only uses the type parameter for input (or only uses it for output), you can’t specify the in or out modifiers. Only interfaces and delegates can have variant type parameters. Firstly the CLR doesn’t allow it. From the conceptual point of view Interfaces represent a way of looking at an object from a particular perspective, whereas classes are more actual implementation types.

提交回复
热议问题