填写在C#中的数组 [英] fill an array in C#

查看:159
本文介绍了填写在C#中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中有大约18静态补在类阵列服务于一个值赋给数组中的每个元素的方法。我在寻找一个相当于C#来达到同样的事情,但我没有找到使用相同的紧凑什么:

1)的ForEach我了解按值传递数组中的元素,所以我不能改变他们

2)可枚举重复创建新的数组,这似乎是开销来创建一个新的数组,然后每个元素从数组复制

3)for循环不是pretty,我猜就是为什么Java的乡亲介绍了这款紧凑型符号开始以

4)从Array类的清除方法可以设置一切为零,但我怎么转换零到非零值我想要什么?

要演示Java的语法考虑这个code,打印三倍的数字7:

  INT [] III = {1,2,3};
Arrays.fill(三,7);
对于(INT I:III){
    的System.out.println(ⅰ);
}


解决方案

编写自己的扩展方法

 公共静态类ArrayExtensions {
    公共静态无效的填充和LT; T>(这件T [] originalArray,T带){
        的for(int i = 0; I< originalArray.Length;我++){
            originalArray [I] =用;
        }
    }
}

和使用它像

  INT为foo [] =新INT [] {0,0,0,0,0};
foo.Fill(13);

将填补所有的元素以13

In Java there are about 18 a static "fill" methods in the class Arrays that serve to assign one value to each element in an array. I'm looking for an equivalent in C# to achieve the same thing but I'm not finding anything with the same compactness:

1) ForEach as I understand passes elements in the array by value so I can't change them

2) Repeat from Enumerable creates a new array, it seems to be overhead to create a new array and then copy each element from the array

3) a for-loop isn't pretty, which I guess is why the Java folks introduced this compact notation to begin with

4) The Clear method from the Array class can set everything to zero, but then how do I convert zero to the non-zero value I want?

To demonstrate Java's syntax consider this code that prints three times the number 7:

int[] iii = {1, 2, 3};
Arrays.fill(iii, 7);
for (int i : iii) {
    System.out.println(i);
}

解决方案

Write yourself an extension method

public static class ArrayExtensions {
    public static void Fill<T>(this T[] originalArray, T with) {
        for(int i = 0; i < originalArray.Length; i++){
            originalArray[i] = with;
        }
    }  
}

and use it like

int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);

will fill all the elements with 13

这篇关于填写在C#中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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