gpt4 book ai didi

c# - 如何重构 "using"语句以避免代码重复?

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:07 25 4
gpt4 key购买 nike

假设我有以下方法:

 public string GetSchedules(string request)
{
using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint))
{
return soapClient.GetSchedules(AuthenticationInfo, request);
}
}

public string GetCountryList(string request)
{
using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint))
{
return soapClient.GetCountryList(AuthenticationInfo, request);
}
}

public string GetCarriers(string request)
{
using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint))
{
return soapClient.GetCarriers(AuthenticationInfo, request);
}
}

如您所见,唯一不同的是所调用方法的名称。我如何重构这些方法以仅应用一次“using”语句并避免代码重复?

最佳答案

对我来说,你所拥有的很好,但如果你想将它们排除在外,你可以使用 Func和 lambda 。沿着这些线的东西:

public string GetSchedules(string request)
{
return Worker((c) => c.GetSchedules(AuthenticationInfo, request));
}

public string GetCountryList(string request)
{
return Worker((c) => c.GetCountryList(AuthenticationInfo, request));
}

public string GetCarriers(string request)
{
return Worker((c) => c.GetCarriers(AuthenticationInfo, request));
}

private string Worker(Func<SoapClientClassGoesHere, string> f)
{
using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint))
{
return f(soapClient);
}
}

Func<A, R>意思是“一个接受类型为 A 的参数并返回一个类型为 R 的值的函数”(对于一个接受两个 参数的函数,你可以有 Func<A, B, R>,等等)。

更多关于 Func<>和 lambdas 在 this questionthis question (还有很多,这是一个内容丰富的话题)。

这是一个 live example on ideone.com (一个非常愚蠢的实例,但它演示了这个概念):

using System;
using System.Collections.Generic;

class Foo {
public string GetSchedules(string request)
{
return Worker((c) => c[request]);
}

public string GetCountryList(string request)
{
return Worker((c) => c[request].ToUpper());
}

public string GetCarriers(string request)
{
return Worker((c) => c[request].ToLower());
}

private string Worker(Func<Dictionary<string,string>, string> f)
{
var d = new Dictionary<string, string>();
d.Add("1", "One");
d.Add("2", "Two");
d.Add("3", "Three");
return f(d);
}
}

public class Test
{
public static void Main()
{
var f = new Foo();
Console.WriteLine(f.GetSchedules("1"));
Console.WriteLine(f.GetCountryList("1"));
Console.WriteLine(f.GetCarriers("1"));
}
}

关于c# - 如何重构 "using"语句以避免代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com