【发布时间】:2020-10-30 02:34:03
【问题描述】:
我有以下两种方法:
private string Post(string url, ByteArrayContent content, AuthenticationToken token = null) {
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using HttpClient client = new HttpClient();
if (token != null) {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Access_token);
}
return client.PostAsync(url, content)
.Result.Content.ReadAsStringAsync()
.Result;
}
private string Put(string url, ByteArrayContent content, AuthenticationToken token) {
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using HttpClient client = new HttpClient();
if (token != null) {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Access_token);
}
return client.PutAsync(url, content)
.Result.Content.ReadAsStringAsync()
.Result;
}
如您所见,唯一的区别是一个方法调用PostAsync,而另一个方法调用PutAsync。
是否可以编写一个函数,例如:
private string Send(string url, ByteArrayContent content, AuthenticationToken token, String functionName) {
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using HttpClient client = new HttpClient();
if (token != null) {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Access_token);
}
return client[sendFunction](url, content)
.Result.Content.ReadAsStringAsync()
.Result;
}
然后我就可以将其他每个功能变成一个衬里,例如:
private string Post(string url, ByteArrayContent content, AuthenticationToken token = null) {
this.Send(url, content, token, "PostAsync");
}
...如果我能以一种类型安全的方式传递函数或函数名,那就更好了。
【问题讨论】:
标签: c# rest functional-programming refactoring code-duplication