c# – 转换简单的通用对象
发布时间:2020-12-16 01:54:02 所属栏目:百科 来源:网络整理
导读:我有一个方法,我为简化使用HttpClient调用而创建.它使用方法HttpReponse.Content.ReadAsAsync().Result来获取API的响应. 一切正常.我的方法看起来像这样: public static T ExecuteAPIGetRequestT(string url,Dictionarystring,string parameters) { HttpCli
我有一个方法,我为简化使用HttpClient调用而创建.它使用方法HttpReponse.Content.ReadAsAsync().Result来获取API的响应.
一切正常.我的方法看起来像这样: public static T ExecuteAPIGetRequest<T>(string url,Dictionary<string,string> parameters) { HttpClient client = new HttpClient(); //basic authentication var t = new object(); string baseURL = "myurl"; //Execute request HttpResponseMessage response = client.GetAsync(baseURL).Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsAsync<T>().Result; } else { return (T)t; } } 我的问题是,如果查询失败,它需要返回一个空类型的T.如果它是我编写的自定义类,这很好,但它不适用于像string或string []这样的对象.有任何想法吗? 干杯 大斑病 解决方法
尝试返回默认值(T)
if (response.IsSuccessStatusCode) { return response.Content.ReadAsAsync<T>().Result; } else { return default(T); } 对于引用类型,default将返回null,并且为自定义struct和enum将零值等于int,double等等.以及相应的默认值. Daniel注意到一个问题:如果对于引用类型,您希望返回默认对象而不是null,则应该定义泛型约束new T().现在,您可以使用对无参数构造函数的调用来实例化类型为T的对象.完整方法如下: public static T ExecuteAPIGetRequest<T>(string url,string> parameters) where T : new() { HttpClient client = new HttpClient(); //basic authentication string baseURL = "myurl"; HttpResponseMessage response = client.GetAsync(baseURL).Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsAsync<T>().Result; } else { return new T(); //returns an instance,not null } } 现在,您将返回引用类型的默认对象,而不是null. Open类型T只能接受类型,默认情况下有构造函数(没有参数) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容