我有一个
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();
这篇关于我如何投射 List<T>有效地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么我不应该总是在 C# 中使用可空类型Why shouldn#39;t I always use nullable types in C#(为什么我不应该总是在 C# 中使用可空类型)
C# HasValue vs !=nullC# HasValue vs !=null(C# HasValue vs !=null)
C# ADO.NET:空值和 DbNull —— 有没有更高效的语法C# ADO.NET: nulls and DbNull -- is there more efficient syntax?(C# ADO.NET:空值和 DbNull —— 有没有更高效的语法?)
如何在c#中将空值设置为int?How to set null value to int in c#?(如何在c#中将空值设置为int?)
使用 Min 或 Max 时如何处理 LINQ 中的空值?How to handle nulls in LINQ when using Min or Max?(使用 Min 或 Max 时如何处理 LINQ 中的空值?)
在 C# 中如果不为 null 的方法调用Method call if not null in C#(在 C# 中如果不为 null 的方法调用)