类似于my previous question但也与this question relating to methods with different parameters有关,我想执行以下操作:
我有一个
中的HttpClient变量HttpClient client= new HttpClient();
现在,我们知道它具有不同的方法,例如PostAsync
和DeleteAsycn
。您可能会注意到,此类函数的参数不同。 (例如PostAsync
包含DeleteAsync
没有的内容)
我想拥有一个可以容纳所有这些功能的变量(取决于它可能是Post还是Delete或Get等的情况)
我该怎么做?
答案 0 :(得分:-1)
我建议您采用以下方法(我正在动态编写代码,我尚未对其进行测试,因此可能容易出错,请亲自检查一下):
public class IHttpDelegate {
void run();
}
public abstract class HttpDelegate : IHttpDelegate {
public HttpClient httpClient;
public HttpDelegate(Uri uri) {
this.httpClient = new HttpClient(uri);
}
protected httpClient {
get {
return this.httpClient ;
}
}
}
public class HttpPostDelegate : HttpDelegate {
private HttpContect httpContent;
public HttpPostDelegate (Uri uri) : base(uri) {
this.httpContent = httpContent;
}
public HttpContect httpContent {
get {
return this.httpContent;
}
}
public void run() {
httpClient.PostAync(httpContent);
}
}
public class HttpDeleteDelegate : HttpDelegate {
public HttpDeleteDelegate (Uri uri) : base(uri) {
}
public void run() {
httpClient.DeleteAync();
}
}
然后,您应该基于 IHttpDelegate 接口定义一个委托。
我希望对您有所帮助!