大佬教程收集整理的这篇文章主要介绍了c# – 转换简单的通用对象,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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 []这样的对象.有任何想法吗?
干杯
大斑病
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 } }
以上是大佬教程为你收集整理的c# – 转换简单的通用对象全部内容,希望文章能够帮你解决c# – 转换简单的通用对象所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。