如何填充/实例化单个值的C#数组? [英] How to populate/instantiate a C# array with a single value?

查看:126
本文介绍了如何填充/实例化单个值的C#数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,在C#中值类型的实例化阵列自动与默认值填充类型(如BOOL FALSE,0 INT,等等等等)。

I know that instantiated arrays of value types in C# are automatically populated with the default value of the type (eg false for bool, 0 for int, etc etc).

有没有办法来自动填充用的种子值,这不是默认的数组?无论是在创建或内置的方法之后(我相信Java有类似Array.Fill(),它做到这一点)?说我想要的,而不是虚假的布尔数组,这是默认为true。是否有一个内置的方式做到这一点,或者你只需​​要通过数组用for循环迭代?

Is there a way to autopopulate an array with a seed value that's not the default? Either on creation or a built in method afterwards (I believe Java has something like Array.Fill() which does this)? Say I wanted an boolean array that was true by default, instead of false. Is there a built in way to do this, or do you just have to iterate through the array with a for loop?

 //Example pseudo-code:
 bool[] abValues = new[1000000];
 Array.Populate(abValues, true);

 // Currently how i'm handling this:
 bool[] abValues = new[1000000];
 for (int i = 0; i < 1000000; i++)
 {
     abValues[i] = true;
 }

有通过数组进行迭代和重置的每个值设置为true似乎ineffecient。反正是有解决这个?也许通过翻转的所有值?

Having to iterate through the array and "reset" each value to true seems ineffecient. Is there anyway around this? Maybe by flipping all values?

出键入这个问题,并思考它后,我猜测,默认值是简单的C#如何处理幕后的这些对象的内存分配的结果,所以我想它可能无法做到这一点。但我还是想知道肯定!

After typing this question out and thinking about it, I'm guessing that the default values are simply a result of how C# handles the memory allocation of these objects behind the scenes, so I imagine it's probably not possible to do this. But I'd still like to know for sure!

推荐答案

不知道一个框架的方法,但你可以写一个快速的帮手为你做它。

Don't know of a framework method but you could write a quick helper to do it for you.

public static void Populate<T>(this T[] arr, T value ) {
  for ( int i = 0; i < arr.Length;i++ ) {
    arr[i] = value;
  }
}

这篇关于如何填充/实例化单个值的C#数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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