当T为集合类型时,如何让CallWebApi泛型方法返回集合而非null?
修改泛型异步方法CallWebApi,NotFound时返回空集合而非null
原方法在遇到HttpStatusCode.NotFound时返回default(T),对于集合类型(如List<T>、IEnumerable<T>)会返回null,我们需要修改逻辑,让集合类型返回空实例而非null,非集合类型保持原有返回default(T)的行为。
解决方案代码
public static async Task<T> CallWebApi<T>(string url, string accessToken) { var response = await httpClient.GetAsync(url); if (response.StatusCode == HttpStatusCode.NotFound) { Type targetType = typeof(T); // 处理数组类型:返回长度为0的数组 if (targetType.IsArray) { return (T)Activator.CreateInstance(targetType, 0); } // 处理泛型集合类型(实现IEnumerable<>的类型) bool isGenericCollection = targetType.IsGenericType && typeof(IEnumerable<>).IsAssignableFrom(targetType.GetGenericTypeDefinition()); if (isGenericCollection) { if (targetType.IsInterface) { // 针对集合接口(如IEnumerable<T>、IList<T>),返回对应的空具体集合 Type itemType = targetType.GetGenericArguments()[0]; Type emptyListType = typeof(List<>).MakeGenericType(itemType); return (T)Activator.CreateInstance(emptyListType); } else { // 针对具体集合类型(如List<T>、HashSet<T>),直接创建空实例 return Activator.CreateInstance<T>(); } } // 非集合类型返回default(T) return default(T); } // 其他状态码的处理逻辑(请补充原代码中省略的部分) // ... }
逻辑说明
- 数组处理:通过
Activator.CreateInstance创建长度为0的数组,确保数组类型返回空数组而非null。 - 泛型集合判断:检查类型是否为泛型且实现了
IEnumerable<>接口,覆盖大部分常见集合类型。 - 集合接口处理:如果T是集合接口(如
IEnumerable<TItem>),创建对应的List<TItem>空实例并转换为接口类型返回,保证类型兼容。 - 具体集合类型处理:如果T是具体集合类(如
List<T>、HashSet<T>),直接通过Activator.CreateInstance<T>创建空实例(前提是该集合有无参构造函数,内置集合均满足)。 - 非集合类型:保持原有逻辑,返回
default(T),不影响值类型和非集合引用类型的行为。
内容的提问来源于stack exchange,提问作者Earth
相关产品推荐
相关产品推荐

