是否Array.ToArray<>()返回原来的数组,如果是同样的类型? [英] Does Array.ToArray<>() return the original array if it is the same type?

查看:118
本文介绍了是否Array.ToArray<>()返回原来的数组,如果是同样的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应付每天一个框架,我们有时会提供接受的IEnumerable<方法; MyBusinessObject> 作为以显示用户界面的参数,执行计算等

I deal with a framework on a daily basis where we sometimes provide methods that accept IEnumerable<MyBusinessObject> as a parameter in order to show user interfaces, perform calculations etc.

如果我通过在 MyBusinessObject 的这样一个数组:

If I pass in an array of MyBusinessObject like so:

MyBusinessObject[] myArray = new MyBusinessObject { obj1, obj2, ..., objN };
frameworkClass.MyMethod(myArray);

....

public class FrameworkClass
{
    public void MyMethod(IEnumerable<MyBusinessObject> objs)
    {
        // Other code that uses the enumerable
        MyBusinessObject[] objectArray = objs.ToArray();            
        // More code that uses the enumerable
    }
}



<更多代号P >是否行 objs.ToArray()简单解析的IEnumerable< MyBusinessObject> 回原来的阵列,或不它把它复制到一个全新的阵列,可以使用了?

Does the line objs.ToArray() simply resolve the IEnumerable<MyBusinessObject> back to the original array, or does it copy it to a whole new array, ready for use?

推荐答案

不,你的总是得到的阵列的一个新的副本,但在它的对象不拷贝,它们是作为原始阵列中的相同的标号

No, you will always get a new copy of the array, though the objects in it aren't copies, they are the same references as in the original array.

这将是非常不一致的改变返回数组的有时的影响源,有时不是。 了ToList 适用于同样的原因是一样的。

It would be very inconsistent for changes to the returned array to sometimes affect the source and sometimes not. ToList works the same way for the same reason.

您可以查看源代码(截至2015年),如果您需要查看细节: Enumerable.ToArray 这反过来又创造元素的副本(用于的ICollection 进行了优化,因此 []数组,但仍使复印件)内部 Buffer类

You can check source code (as of 2015) if you need to review details: Enumerable.ToArray which in turn creates copy of elements (optimized for ICollection and hence Array[], but still making copy) with internal Buffer class.

这篇关于是否Array.ToArray&LT;&GT;()返回原来的数组,如果是同样的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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