Enumerable.Repeat用于引用类型对象的初始化 [英] Enumerable.Repeat for reference type objects initialization

查看:330
本文介绍了Enumerable.Repeat用于引用类型对象的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Enumerable.Repeat函数有疑问.

I have a question about Enumerable.Repeat function.

如果我要上课:

class A
{
//code
}

然后我将创建一个具有对象类型的数组:

And I will create an array, of that type objects:

A [] arr = new A[50];

接下来,我要初始化这些对象,调用Enumerable.Repeat:

And next, I will want to initialize those objects, calling Enumerable.Repeat:

arr = Enumerable.Repeat(new A(), 50);

这些对象在内存中是否具有相同的地址? 例如,如果我要检查其哈希代码,则:

Will those objects have the same address in memory? If I will want to check their hash code, for example in that way:

bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();

这将使我返回true,如果我要更改一个对象的属性,那么所有其他对象也将对其进行更改.

This will return me true, and if I will change one object properties, all other objects will change it too.

所以我的问题是:初始化引用类型对象是否正确?如果没有,那有什么更好的方法?

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

推荐答案

以这种方式使用Enumerable.Repeat将仅初始化一个对象,并在每次遍历结果时都返回该对象.

Using Enumerable.Repeat this way will initialize only one object and return that object every time when you iterate over the result.

这些对象在内存中的地址是否相同?

Will those objects have the same address in memory?

只有一个对象.

要实现您想要的目标,可以执行以下操作:

To achieve what you want, you can do this:

Enumerable.Range(1, 50).Select(i => new A()).ToArray();

这将返回由50个类型为A的不同对象组成的数组.

This will return an array of 50 distinct objects of type A.

顺便说一句,GetHashCode()返回相同值的事实并不意味着这些对象在引用上是相等的(或者就此而言简单地相等).两个不相等的对象可以具有相同的哈希码.

By the way, the fact that GetHashCode() returns the same value does not imply that the objects are referentially equal (or simply equal, for that matter). Two non-equal objects can have the same hash code.

这篇关于Enumerable.Repeat用于引用类型对象的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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