C# :具有不同定义的方法的通用方法/包装器

例如,我有以下方法:


    private async Task<T> Read<T>(string id, string endpoint)

    {

         //....

    }


    private async Task<List<T>> List<T>(int start, int count, string endpoint, List<FilterData> filterData = null)

    {

         //....

    }

(以及更多具有不同属性的内容)但是所有这些方法都可以抛出 如果我调用方法抛出这个异常,我想执行一些逻辑并调用调用的方法。即:BillComInvalidSessionException


    private async Task<T> ReadWithRetry<T>(string id, string endpoint)

    {

        try

        {

            return await Read<T>(id, endpoint);

        }

        catch (BillComInvalidSessionException)

        {

            SessionId = new Lazy<string>(() => LoginAsync().Result);

            return await ReadWithRetry<T>(id, endpoint);

        }

    }


    private async Task<List<T>> ListWithRetry<T>(int start, int count, string endpoint, List<FilterData> filterData = null)

    {

        try

        {

            return await List<T>(start, count, endpoint, filterData);

        }

        catch (BillComInvalidSessionException)

        {

            SessionId = new Lazy<string>(() => LoginAsync().Result);

            return await ListWithRetry<T>(start, count, endpoint, filterData);

        }

    }

如何创建一个通用方法,它将执行相同的逻辑,但获得不同的方法作为参数?


ITMISS
浏览 109回答 1
1回答

暮色呼如

您可以通过使用泛型委托来实现此目的:private async Task<T> Retry<T>(Func<Task<T>> func){&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return await func();&nbsp; &nbsp; }&nbsp; &nbsp; catch (BillComInvalidSessionException)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; SessionId = new Lazy<string>(() => LoginAsync().Result);&nbsp; &nbsp; &nbsp; &nbsp; return await Retry(func);&nbsp; &nbsp; }}然后,您的重试方法将转到:private async Task<T> ReadWithRetry<T>(string id, string endpoint){&nbsp; &nbsp; return await Retry(async () => await Read<T>(id, endpoint));}private async Task<List<T>> ListWithRetry<T>(int start, int count, string endpoint, List<FilterData> filterData = null){&nbsp; &nbsp; return await Retry(async () => await List<T>(start, count, endpoint, filterData));}
打开App,查看更多内容
随时随地看视频慕课网APP