当您想要更改的所有内容都是返回类型时,重载方法的最佳方法

eva*_*nal 4 .net c# overloading overload-resolution

由于返回类型不能用于消除方法的歧义,当你想要改变的只是返回类型时,什么是最简洁/最好的方法来重载方法?下面是一些示例代码;

public static string Get(string url, Guid id, bool logResponse = true, bool baseKey = false)
{
     Tuple<string, int> response = Get(url, id, true, logResponse, baseKey);

     if (response.Item2 > 399)
        return null;
     return response.Item1;
}


public static Tuple<string, int> Get(string url, Guid id, bool returnStatus, bool logResponse = true, bool baseKey = false)
{
    // leaving out lots of code in this method, you should be able to get the point without it
    int http_status;  
    string response = CallApi(url, key, "GET", out http_status);

    return new Tuple<string, int>(response, http_status);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作,但我有一个额外的param(returnStatus),没有任何目的,它只在那里,所以编译器可以告诉两种方法之间的区别.有没有更好的方法来做到这一点,还是我只是添加无用的参数?

Ser*_*kiy 10

更改方法名称,例如

string Get(string url, Guid id, bool logResponse)
Tuple<string, int> GetWithStatus(string url, Guid id, bool logResponse)
Run Code Online (Sandbox Code Playgroud)

编程的主要目标不是告诉编译器有什么不同,而是告诉开发人员将会读取你的代码.另一个选项是返回状态作为out参数:

string Get(string url, Guid id, bool logResponse, out int status)
Run Code Online (Sandbox Code Playgroud)

我不太喜欢out参数,但我更喜欢元组 - 什么会告诉Item2开发人员使用你的方法的名字?是状态,重试计数,还是响应长度?方法名称和返回类型都不能说它是什么.

因此,即使对于重命名方法的第一种情况,我也将返回类型更改为类似

public class ServerResponse
{
    public string Content { get; set; }
    public HttpStatusCode Status { get; set; } // enum

    // use this in first method to check if request succeed
    public bool IsError
    {
       get { return (int)Status > 399; }
    }
}
Run Code Online (Sandbox Code Playgroud)