# 枚举.重复有一些内存问题吗?[英] Enumerable.Repeat has some memory issues? ### 问题描述

```Double[][] myarr = Enumerable.Repeat(new double, 13).ToArray();
```

```myarr++;
```

```myarr[i] = new double;
```

## 推荐答案

```double[][] myarr = Enumerable.Range(0, 13)
.Select(ignored => new double)
.ToArray();
```

## 其他推荐答案

with new double您正在创建对双打数组的引用，然后重复参考 12次，因此Myarr [0..n]将参考一个内存区域.

```static T[][] CreateArray<T>(int rows, int cols)
{
T[][] array = new T[rows][];
for (int i = 0; i < array.GetLength(0); i++)
array[i] = new T[cols];

return array;
}
```

```public static IEnumerable<TResult> RepeatAction<TResult>(Action<TResult> elementAction, int count)
{
for (int i = 0; i < count; i++)
{
yield return elementAction();
}
yield break;
}
usage
RepeatAction(()=>new double, 12);
```

## 其他推荐答案

### 问题描述

I initialized an Array as

```Double[][] myarr = Enumerable.Repeat(new double, 13).ToArray();
```

Then in a loop i am incrementing values like

```myarr++;
```

This causes all values like myarr, myarr, myarr ..... myarr to increment by one.

This problem is not occurring when using a for loop (0-12) i am initializing like

```myarr[i] = new double;
```

Why is this so?

## 推荐答案

Other answers have explained the problem. The solution is to create a new array on each iteration, e.g.

```double[][] myarr = Enumerable.Range(0, 13)
.Select(ignored => new double)
.ToArray();
```

## 其他推荐答案

With new double you are creating reference to array of doubles, and then you repeate the reference 12 times, so myarr[0..n] will have reference to one memory region.

You can use the folowing method to resolve thw issue

```static T[][] CreateArray<T>(int rows, int cols)
{
T[][] array = new T[rows][];
for (int i = 0; i < array.GetLength(0); i++)
array[i] = new T[cols];

return array;
}
```

Or with custom Repeat method which calls action every step:

```public static IEnumerable<TResult> RepeatAction<TResult>(Action<TResult> elementAction, int count)
{
for (int i = 0; i < count; i++)
{
yield return elementAction();
}
yield break;
}
usage
RepeatAction(()=>new double, 12);
```

## 其他推荐答案

It's because new double creates a single array object in memory - Enumerable.Repeat is simply providing you with multiple references to that array.