如何在C# System.Linq Lambda表达式中实现对象多重类型转换?
解决方案
你可以通过LINQ链式调用实现多重类型转换并提取目标属性,以下是两种实现方式:
安全转换(推荐)
这种写法会过滤掉转换失败的项,避免空引用异常:
var meshGuidList = TerrainData.MeshCollection .Cast<TreeGridItem>() // 将集合项统一转换为TreeGridItem类型 .Select(meshcol => meshcol.Tag as Globals.MeshProperty) // 安全转换Tag为MeshProperty .Where(meshprop => meshprop != null) // 过滤转换失败的null实例 .Select(meshprop => meshprop.MeshGuid) // 提取MeshGuid属性 .ToList();
强制转换(仅当确定所有项都能成功转换时使用)
如果能保证所有集合项都可转换为TreeGridItem,且所有Tag都能转换为Globals.MeshProperty,可以用强制转换简化代码,但转换失败会抛出InvalidCastException:
var meshGuidList = TerrainData.MeshCollection .Cast<TreeGridItem>() .Select(meshcol => ((Globals.MeshProperty)meshcol.Tag).MeshGuid) .ToList();
代码说明
Cast<TreeGridItem>():对应原代码foreach循环的类型声明,将集合中每一项转换为TreeGridItem类型。as关键字:执行安全类型转换,转换失败时返回null,不会抛出异常。Where过滤:确保后续只处理转换成功的MeshProperty实例,避免访问MeshGuid时出现空引用问题。
内容的提问来源于stack exchange,提问作者user11095285
相关产品推荐
相关产品推荐

