Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

c# - Enumerable.Repeat for reference type objects initialization

I have a question about Enumerable.Repeat function.

If I will have a class:

class A
{
//code
}

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

A [] arr = new A[50];

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();

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

There is only one object.

To achieve what you want, you can do this:

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...