我如何投射 List<T>有效地?

How do I cast a Listlt;Tgt; effectively?(我如何投射 Listlt;Tgt;有效地?)
本文介绍了我如何投射 List<T>有效地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个

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和.Cast T会返回一个T的列表,但是两种方法的含义不同.

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&lt;T&gt;有效地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)