VB.NET使用Lambda表达式遍历匿名类型集合触发MissingMemberException错误
异常原因与修复方案
错误根源
- 你将匿名类型数组声明为
Object类型,Object类本身不存在ForEach方法,VB后期绑定查找方法失败抛出System.MissingMemberException。常规For Each可以正常运行是因为VB后期绑定支持遍历实现了IEnumerable接口的对象,不需要调用额外方法。 - .NET 数组本身没有实例形式的
ForEach方法,只有Array类的静态ForEach方法;如果要使用实例方法形式调用ForEach,需要引入System.Linq命名空间,将数组转为List<T>后调用List的实例ForEach方法。 - 你的代码还存在两个隐性错误:
String.Format的占位符写成了[0}(应为{0}),匿名类型属性名区分大小写,调用x.model/x.color会触发额外的运行时错误,需和声明时的.Model/.Color保持一致。
修复后代码
' 顶部引入必要命名空间 Imports System.Linq Imports System.Diagnostics ' 不指定As Object,让编译器自动推断强类型匿名数组 Dim car = { New With {Key .Model = "Buick", .Color = "Blue"}, New With {Key .Model = "Volvo", .Color = "Green"}, New With {Key .Model = "Jeep", .Color = "Red"} } ' 原有For Each逻辑不变 For Each item In car If item.Color = "Blue" Then Debug.Print(String.Format("{0} {1}", item.Model, item.Color)) Next ' 写法1:调用Array静态ForEach方法 Array.ForEach(car, Sub(x) Debug.Print(String.Format("{0} {1}", x.Model, x.Color)) End Sub) ' 写法2:转List后调用实例ForEach方法(需要引入System.Linq) car.ToList().ForEach(Sub(x) Debug.Print(String.Format("{0} {1}", x.Model, x.Color)) End Sub)
内容的提问来源于stack exchange,提问作者Malcolm
相关产品推荐
相关产品推荐

