How does Java's use-site variance compare to C#'s declaration site variance?

前端 未结 4 1586
耶瑟儿~
耶瑟儿~ 2020-12-01 03:22

My understand is that specifying variance for generics in C# happens at the type declaration level: when you\'re creating your generic type, you specify the variance for the

4条回答
  •  一向
    一向 (楼主)
    2020-12-01 04:19

    Disadvantages of Java style generics

    One consequence is that the java version only works with reference types(or boxed value-types) and not value-types. IMO that's the biggest disadvantage since it prevents high performance generics in a lot of scenarios and requires manual writing of specialized types.

    It doesn't guarantee an invariant like "This list only contains objects of type x" and needs runtime checks at every getter. The generic type really exists.

    When using reflection you can't ask an instance of a generic object which generic parameters it has.

    Advantages of Java style generics

    You get variance/can cast between different generic parameters.

提交回复
热议问题