具有相似主体的通用和非通用方法

时间:2017-08-10 16:06:08

标签: c# generics optimization

我有一个带有重载的ExecuteAsyncServiceRequest方法,你会注意到这两种方法的主体是相似的。我发现自己想知道是否有更简洁的方法来编写这些方法?具体来说,不必在方法体中重复自己。

提前致谢!

    /// <summary>
    /// Executes an async service request which returns a response of type TResponse
    /// </summary>
    /// <param name="execute">The service request to execute</param>
    /// <param name="success">Callback when the service request is successful</param>
    /// <param name="failure">Callback when the service request fails</param>
    /// <typeparam name="TResponse">Type of the expected ServiceResult returned from the async request</typeparam>
    protected async void ExecuteAsyncServiceRequest<TResponse>(Func<Task<ServiceResult<TResponse>>> execute,
                                                            Action<TResponse> success,
                                                            Action<string> failure)
    {
        ServiceResult<TResponse> result = await execute();

        if (result.ResultCode == ServiceResult.ServiceResultCode.Failed)
            failure(result.FailureDetails);

        success(result.Response);    
    }

    /// <summary>
    /// Executes an async service request
    /// </summary>
    /// <param name="execute">The service request to execute</param>
    /// <param name="success">Callback when the service request is successful</param>
    /// <param name="failure">Callback when the service request fails</param>       
    protected async void ExecuteAsyncServiceRequest(Func<Task<ServiceResult>> execute,
                                                    Action success,
                                                    Action <string> failure)
    {
        ServiceResult result = await execute();

        if (result.ResultCode == ServiceResult.ServiceResultCode.Failed)
            failure(result.FailureDetails);

        success();
    }

1 个答案:

答案 0 :(得分:1)

没有。不幸的是,这是由于.NET本身的类型系统的限制 - 具体而言,void不是一种类型。

具有更多功能影响的语言(与传统的OOP相反)往往没有void的概念;相反,存在一个具有单个值的特殊类型(通常称为unit)。像这样:

public sealed class Unit {
  private Unit() { }
  public static Unit Instance { get; } = new Unit();
}

您可以使用与您的代码类似的功能,但不管它是否值得,都取决于您:

protected async void ExecuteAsyncServiceRequest(Func<Task<ServiceResult>> execute,
                                                Action success,
                                                Action <string> failure) =>
    ExecuteAsyncServiceRequest(
        async () => new ServiceResult<Unit>(await execute(), Unit.Instance),
        _ => success(),
        failure);

这假设ServiceResult<T>可以有一个(可能是internal)构造函数,它将ServiceResult作为参数并复制其所有属性,除了实际的&#34;结果&#34;这是从第二个构造函数参数复制的。