C# Overload return type - recommended approach

2019-01-26 09:46发布

问题:

I have a situation where I just want the return type to be different for a method overload, but you can't do this in C#.

What's the best way to handle this? Is the fact that I need this mean my program structure flawed?

Given the fact that this is impossible in C#, what is the recommended approach?

回答1:

Typically you simply give the methods different names.

An example of this is IDataReader with GetInt32, GetInt64 etc.

To be honest, I believe this usually makes it clearer what you're trying to do anyway - particularly if you're then calling an overloaded method with the result:

Console.WriteLine(reader.GetInt32()); // This is clear

Console.WriteLine(foo.OverloadedGet()); // Which overload of OverloadedGet?


回答2:

Given the fact that this is impossible in C#, what is the recommended approach?

It depends on why you need this.

The most common approach is to just use a different name. The framework does this in many cases, such as the Convert class.

If you want to support multiple types, you can do this via generic methods:

T SomeMethod<T>()
  // Optionally add constraints:"
  where T : IFoo
{

The generic method approach is common for repostories, as it's common that there's an "Entity" type of base class.



回答3:

You can have another parameter specifying the return type.

public static T[] Method1<T>(int i, T type)
{
    return new T[i];
}


回答4:

I've already posted an answer, but here's another way: use object's.

object TheMethod(MyEnum type)
{
    if (type == MyEnum.A) return (object)SubMethod1();
    else if (type == MyEnum.B) return (object)SubMethod2();
    //...
}

int SubMethod1() { return 1; }
string SubMethod2() { return "a"; }

And cast the result to the appropriate type.