具有不同数量参数的代表

Delegates with varying number of parameters

我编写了一个 DLL,它调用了我无权访问的第三方 API。

由于用户可以退出和重新启动应用程序的方式,每个方法都有很多围绕检查访问和刷新令牌的逻辑,以便通过 API 进行身份验证。 (以及错误处理过程)这导致每个不同的 API 调用产生大量重复代码。

我想重构它,这样我就可以将我想要的响应对象类型传递给一个名为 ExecuteApiCall 的通用方法。然后可以为特定的 REST 调用调用适当的方法。

我创建了具有以下签名的方法:

private T ExecuteApiCall<T>(string name, Action<T> requestCall) where T : IApiResponse, new()

这正如我所料。我现在遇到的问题是一些请求需要额外的参数,我无法将不同数量的参数传递给 Action 委托。

我该如何处理这个问题?

我想换成

Action<T, ApiRequestParameters>

其中 ApiRequestParameters 是所有可能参数的 class,public 面向方法可以在调用私有 ExecuteApiCall 之前设置它需要的内容。但这并不是真正的最佳实践。

我真的希望这对某人有意义并提前致谢。如果需要,很乐意提供更多代码示例。

以下需要处理

ExecuteCallA()
{
    //The API call is done here using RestSharp
}

ExecuteCallB(string aParameter)
{
    //The API call is done here using RestSharp
}

ExecuteCallC(string aParameters, int anotherParameter)
{
    //The API call is done here using RestSharp
}

或者将 Action 设置为类似这样会更容易吗?

Action<T, object, object, object>

这样它就可以处理额外的参数并忽略任何它不需要的参数。

编辑:

感谢 Sean 的建议,这可能是我要采用的方法。我的另一个选择,再次不确定此处的最佳做法...

将使 public 签名包含方法参数并将它们设置为私有字段。

private string myParameter;
public ApiResponseA GetWhatever(string a)
{
    myParameter = a;
    ExecuteApiCall<ApiResponseA>();
    myParameter = null;
}

然后更改负责实际 API 调用的私有方法以使用私有字段而不是参数。想法?

我会为一定数量的参数添加重载。例如:

private T ExecuteApiCall<T>(string name, Action<T> requestCall) where T : IApiResponse, new();

private T ExecuteApiCall<P1, T>(string name, P1 p1, Action<P1, T> requestCall) where T : IApiResponse, new()

private T ExecuteApiCall<P1, P2, T>(string name, P1 p1, P2 p2, Action<P1, P2, T> requestCall) where T : IApiResponse, new()

// etc

实施起来有点重复,但一旦完成,您就可以忘掉它,这将使您向用户展示的 API 更加清晰和可预测。