为何无法在RunWorkerCompleted事件中遍历e.Result返回的Dictionary对象
问题原因
BackgroundWorker组件的DoWorkEventArgs.Result和RunWorkerCompletedEventArgs.Result属性的默认类型都是object,你将Dictionary<string, int>类型对象赋值给e.Result时会发生装箱操作,对象会被向上转型为object类型- 你在
_DoWork事件中遍历的是未装箱的原始Dictionary<string, int>类型对象,该类型实现了IEnumerable接口支持遍历;但到_RunWorkerCompleted事件中取到的e.Result是object类型,object没有实现GetEnumerator方法,因此无法直接用于foreach遍历,就会抛出你遇到的CS1579错误。
解决方案
在遍历前先将e.Result强制转换回Dictionary<string, int>类型即可,建议增加异常、类型和空值判断提升代码健壮性,示例代码如下:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // 先判断后台操作是否抛出异常 if (e.Error != null) { // 自定义异常处理逻辑 return; } // 类型匹配判断+转换,C# 7.0及以上版本支持模式匹配写法 if (e.Result is Dictionary<string, int> myDictionary) { foreach (KeyValuePair<string, int> kvp in myDictionary) { // 你的遍历业务逻辑 } } }
如果使用的C#版本不支持模式匹配,可以用传统强转写法:
Dictionary<string, int> myDictionary = e.Result as Dictionary<string, int>; if (myDictionary != null) { foreach (KeyValuePair<string, int> kvp in myDictionary) { // 你的遍历业务逻辑 } }
内容的提问来源于stack exchange,提问作者Matic-C
相关产品推荐
相关产品推荐

