C# Covariance on subclass return types

前端 未结 4 1438
清酒与你
清酒与你 2020-11-29 10:41

Does anyone know why covariant return types are not supported in C#? Even when attempting to use an interface, the compiler complains that it is not allowed. See the followi

4条回答
  •  [愿得一人]
    2020-11-29 11:11

    Eric Lippert has written a few posts on this site about return method covariance on method overrides, without as far as I can see addressing why the feature is unsupported. He has mentioned, though, that there are no plans to support it: https://stackoverflow.com/a/4349584/385844

    Eric is also fond of saying that the answer to "why isn't X supported" is always the same: because nobody has designed, implemented, and tested (etc.) X. An example of that is here: https://stackoverflow.com/a/1995706/385844

    There may be some philosophical reason for the lack of this feature; perhaps Eric will see this question and enlighten us.

    EDIT

    As Pratik pointed out in a comment:

    interface IBuilder 
    { 
        T Build(); 
    } 
    

    should be

    interface IBuilder 
    { 
        T Build(); 
    } 
    

    That would allow you to implement PastryOrder : IBuilder, and you could then have

    IBuilder builder = new PastryOrder();
    

    There are probably two or three approaches you could use to solve your problem, but, as you note, return method covariance is not one of those approaches, and none of this information answers the question of why C# doesn't support it.

提交回复
热议问题