现在有一个HttpHelper类
public async Task<string> ExecuteAsync<H>(H header) where H : class, new() { var client = new RestClient(_url); if (!string.IsNullOrWhiteSpace(_accountSid) && !string.IsNullOrWhiteSpace(_secretKey)) { client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey); } var headerString = JsonConvert.SerializeObject(header); Dictionary<string, string> headerParameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(headerString); RestRequest request = new RestRequest(); if (headerParameters != null) { foreach (var p in headerParameters) { request.AddHeader(p.Key, p.Value); } } var response = await client.ExecuteAsync(request, Method.GET); return response.Content; } public async Task<string> ExecuteAsync<T>(T data, bool isFrom = true) where T : class, new() { if (data == null) return ""; var client = new RestClient(_url); var dataString = JsonConvert.SerializeObject(data); RestRequest request = new RestRequest(); if (isFrom) { Dictionary<string, string> parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataString); foreach (var p in parameters) { request.AddParameter(p.Key, p.Value); } } else { //request.AddHeader("Accept", "application/json"); request.AddJsonBody(dataString); } var response = await client.ExecuteAsync(request, Method.POST); return response.Content; }
这种写法是完全符合规则,但是调用的时候会有点小问题。
第二个方法调用,我们一般会忽略第二个入参,按照定义第二个入参我们设置了默认值,目的就是让在调用的时候省点代码。
如
ExecuteAsync(request)
但是现在因为有另一个重载泛型方法出现,导致调用了第一个方法,是不是有点意外?
所以是不是含泛型参数的方法,不建议使用有默认值的入参?靠北了这是。
那就不重载了重新命个名ExecuteAsyncGet
标签:JsonConvert,ExecuteAsync,C#,request,重载,var,client,泛型,new From: https://www.cnblogs.com/wenthing/p/18108057