Really impossible to use return type overloading?

前端 未结 7 1336
梦如初夏
梦如初夏 2020-11-30 11:20

I made a small DLL in MSIL with two methods:

float AddNumbers(int, int)
int AddNumbers(int, int)

As some of you might know, MSIL allows you

相关标签:
7条回答
  • 2020-11-30 12:20

    MSIL being able to hold both methods in the same assembly has nothing to do with the compiler determining which one to call.

    Covariant return types have been discussed for many years, they are partially allowed in Java, C++ has a special case, and the C# designers have added some minor changes to 4.0.

    For your toy problem, there are simple typical solutions. For instance, your float AddNumbers(int, int) is likely always to be the same as (float) AddNumbers(int, int), in which case there is no need for the second function. Typically that case is handled with generics: <T> AddNumbers(<T> n1, <T> n2), so you'd end up with float AddNumbers(float, float) and int AddNumbers(int, int).

    A real-life scenario is more likely to be where you have different representations you want to return but you don't want to rename the method. In the inheritance/override use case, you can also solve this somewhat with generics.

    In the few cases, where I've wanted to do as you want, it's actually turned out better to name the methods more appropriately since it is more readable and maintainable in the long run.

    This was also discussed already here.

    The case in MSIL/C# at http://blogs.msdn.com/abhinaba/archive/2005/10/07/478221.aspx is special because they are explicit conversion operators.

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