我有以下两种方法:
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,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,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,AuthenticationToken token = null) {
this.Send(url,content,token,"PostAsync");
}
...如果我可以以安全的方式传递函数或函数名称,那将更好。