Really impossible to use return type overloading?

前端 未结 7 1337
梦如初夏
梦如初夏 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:13

    Like everyone else has said, no C# doesn't support this. In fact, the reason IL supports this, is because you have to be explicit about the return types, just like the parameters. For instance, in IL you'd say

    ldarg.0
    ldarg.1
    call int AddNumbers(int, int)
    

    IL doesn't really have a notion of method overloading: float AddNumbers(int, int) has no relation to int AddNumbers(int, int) whatsoever, as far as IL is concerned. You have to tell the IL compiler everything in advance, and it never tries to infer you intent (like higher level languages like C# do).

    Note that most .NET languages and C# make one exception to return type overloading: conversion operators. So

    public static explicit operator B(A a);
    public static explicit operator C(A a);
    

    are compiled to

    public static B op_Explicit(A a);
    public static C op_Explicit(A a);
    

    Because this is such a specific corner case which has to be supported for primitive types (such as int -> bool) and reference type conversions (otherwise you'd get a very pedantic language), this is handled, but not as a case of method overloading.

提交回复
热议问题