简体   繁体   中英

Return types that cannot be overloaded in C#

Why is it not possible to overload functions with return types like Ienumerator?

Is this type treated differently than other types that allow for function overloading?

Return types are not taken into consideration when resolving overloaded methods. There is nothing special in IEnumerator . It's the same for the whole type system. If you want to return different types from one method, you need to declare a base class or interface and return an instance of that type. Afterwards, you can check what's the actual type of the object, cast it and perform specific actions.

public interface IFoo
{
}

public class Bar : IFoo
{
    public void BarMethod() {}
}

public class Biz : IFoo
{
    public void BizMethod() {}
}

Somewhere else you might declare such a method:

public class C
{
    public IFoo M(int i)
    {
        return (i == 0) ? new Bar() : new Biz();
    }
}

And the usage:

C c = new C();
var foo = c.M(1);
var barFoo = foo as Bar;
if (barFoo != null)
{
    barFoo.BarMethod();
}
else
{
    var bizFoo = foo as Biz;
    if (bizFoo != null)
    {
        bizFoo.BizMethod();
    }
}

Simple example of why it wouldn't make sense.

var class Demo
{
    public int GetValue()
    {
        return 3;
    }

    public string GetValue()
    {
        return "3";
    }
}

and the usage

void Main(){
  var demo = new Demo();
  var thing = demo.GetValue();
}

The compiler would have no idea which GetValue() you wanted.

and even if you said its type like

void Main(){
  var demo = new Demo();
  string thing = demo.GetValue();
}

It would not be good coding practice, and would make your use of "var" invalid. Implying a method with the same name can return two different types mean the intention of the code is not clear.

ie in one instance its "this" and another its "that".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM