YummyFood项目中System.ArgumentNullException问题求助
解决System.ArgumentNullException问题
可能的空值触发点分析
你的代码中,以下几个位置都可能导致System.ArgumentNullException:
1. 分类筛选代码段
var foodByCategory = new ObservableCollection<Food>(foodList.Where(food => food.Category.Contains(foodCategory)));
foodList未初始化,为null,调用Where时抛出异常food.Category为null,调用Contains方法时抛出异常foodCategory为null,作为Contains的参数时抛出异常
2. RestService的GetFoodsAsync方法
public async Task<ObservableCollection<Food>> GetFoodsAsync(string uri) { ObservableCollection<Food> foods = null; try { HttpResponseMessage response = await _client.GetAsync(uri); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); foods = JsonConvert.DeserializeObject<ObservableCollection<Food>>(content); } } // 缺少catch块 }
_client未初始化,为null,调用GetAsync前就会抛出异常- 传入的
uri参数为null或空字符串,GetAsync会抛出异常 - 请求失败时
foods保持null,后续使用该返回值会触发空异常 - 缺少异常捕获,无法定位具体错误原因
具体修复步骤
修复分类筛选代码
在调用Contains和Where前增加空值校验,避免异常:
// 先确保foodList不为null,再过滤有效数据 var filteredFoods = foodList?.Where(food => !string.IsNullOrEmpty(food.Category) && !string.IsNullOrEmpty(foodCategory) && food.Category.Contains(foodCategory)) ?? Enumerable.Empty<Food>(); var foodByCategory = new ObservableCollection<Food>(filteredFoods);
修复GetFoodsAsync方法
完善初始化、参数校验和异常处理:
public async Task<ObservableCollection<Food>> GetFoodsAsync(string uri) { // 校验uri参数合法性 if (string.IsNullOrEmpty(uri)) throw new ArgumentException("URI不能为空或null", nameof(uri)); // 初始化空集合而非null,避免后续空引用 ObservableCollection<Food> foods = new ObservableCollection<Food>(); try { // 确保_client已在构造函数中初始化(如 _client = new HttpClient();) HttpResponseMessage response = await _client.GetAsync(uri); // 直接抛出HTTP错误,便于调试 response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); // 反序列化失败时返回空集合 foods = JsonConvert.DeserializeObject<ObservableCollection<Food>>(content) ?? new ObservableCollection<Food>(); } catch (Exception ex) { // 输出异常详情到控制台或日志,方便定位问题 Console.WriteLine("获取数据失败:" + ex.Message + "\n" + ex.StackTrace); // 根据需求选择重新抛出异常或返回空集合 throw; } return foods; }
通用排查建议
- 查看异常堆栈信息:调试时定位到抛出异常的具体行,这是最快定位问题的方式
- 校验所有引用类型变量:确保集合、对象、字符串等都已正确初始化,没有null值
- 本地数据库检查:确认从数据库读取的
Food对象中,Category字段没有null值
内容的提问来源于stack exchange,提问作者Felipe Xavier Diaz
相关产品推荐
相关产品推荐

