是否Enumerable.Cast< T>复制对象? [英] Does Enumerable.Cast<T> Copy Objects?

查看:169
本文介绍了是否Enumerable.Cast< T>复制对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象层次

public class MyBase {}
public class MyDerived : MyBase {}

和有

List<MyBase> myList;

这其实是充满了 MyDerived 的实例

为了访问列表作为列表< MyDerived> ,我做了以下内容:

In order to access that list as a List<MyDerived>, I'm doing the following:

myList.Cast<MyDerived>().ToList()

我读的 Enumerable.Cast< T> ,但它并不清楚,我是否演员LT; T> 了ToList 操作作出新的拷贝到内存中的对象的,或者干脆让编译器的访问的现有的对象,就好像它们是一个列表< MyDerived方式>

I read the MSDN docs on Enumerable.Cast<T>, but it's not clear to me whether the Cast<T> and ToList operations make a new copy of the objects in memory, or simply allow the compiler to access the existing objects as if they were a List<MyDerived>.

推荐答案

正如其名称所暗示的,演员LT; T>()只是蒙上对象:

As its name implies, Cast<T>() just casts objects:

public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) { 
    IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
    if (typedSource != null) return typedSource; 
    if (source == null) throw Error.ArgumentNull("source");
    return CastIterator<TResult>(source);
}

static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) {
    foreach (object obj in source) yield return (TResult)obj; 
} 



在.NET中,它根本不可能复制任意对象。这将毫无意义演员LT; T>()复制的东西。

请注意,如果 T 是值类型,演员LT; T>()将会的复制结构;值类型的总是的复制。 (除非为 REF通过参数)

Note that if T is a value type, Cast<T>() will copy the structs; value types are always copied. (except when passed as ref parameters)

这篇关于是否Enumerable.Cast&LT; T&GT;复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆