How to return subtype in overridden method of subclass in C#?

前端 未结 7 1835
北海茫月
北海茫月 2020-12-09 14:59

I have a subclass with an over-ridden method that I know always returns a particular subtype of the return type declared in the base class. If I write the code this way, it

相关标签:
7条回答
  • 2020-12-09 15:55

    Unfortunately no, covariant return types aren't supported in C# for method overriding. (Ditto contravariant parameter types.)

    If you're implementing an interface you can implement it explicitly with the "weak" version and also provide a public version with the stronger contract. For simple overriding of a parent class, you don't have this luxury I'm afraid :(

    (EDIT: Marc has a reasonable solution - although it's pretty ugly, and method hiding is generally a bad thing for readability. No offence meant, Marc ;)

    I believe this is actually a CLR restriction, not just a language one - but I could well be wrong.

    (As a matter of history, Java (the language) had the same restriction until 1.5 - but it gained covariance at the same time as generics.)

    0 讨论(0)
提交回复
热议问题