我如何投射 List<T>有效地?
- 作者: 你要认真你就输了
- 来源: 51数据库
- 2022-12-08
问题描述
我有一个
List<InputField>
但我需要一个
List<IDataField>
有没有办法在 C# 中进行转换?或者使用 Linq 得到相同的结果?
Is there a way to cast this in c#? Or use Linq to get same result?
我有两个实现相同接口的类:
I have two classes that implement the same interface:
interface IDataField { }
class InputField : IDataField { }
class PurchaseField : IDataField { }
此列表来自 Linq-to-Sql 查询:
This List comes from a Linq-to-Sql query:
List<InputField> list = (from i .... select i).ToList();
推荐答案
Both .OfType
Both .OfType<T> and .Cast<T> will return a list of T, but the meaning of the two methods is different.
list.OfType() 过滤原始列表并返回所有属于 T 类型的项,并跳过不是该类型的项.
list.OfType() filters the original list and returns all items which are of type T, and skips the ones that are not of that type.
list.Cast() 将原始列表中的所有项目转换为 T 类型,并为无法转换为该类型的项目抛出异常.
list.Cast() casts all items in the original list to type T, and throws an exception for items which cannot be cast to that type.
在您的情况下,两者都会给出相同的结果,但使用 .Cast() 会更清楚地传达您的意图,因此我建议使用它.
In your case both would give the same result, but using .Cast() would communicate your intent a lot more clearly, so I would recommend using that.
List<InputField> list = (from i .... select i).Cast<IDataField>().ToList();
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
