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

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

问题描述

我知道 C# 中值类型的实例化数组会自动填充 类型的默认值(例如,bool 为 false,int 为 0 等).

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

有没有办法用非默认的种子值自动填充数组?无论是在创建时还是之后的内置方法(如 Java 的 Arrays.fill())?假设我想要一个默认为 true 而不是 false 的布尔数组.是否有内置的方法可以做到这一点,或者您是否只需要使用 for 循环遍历数组?

Is there a way to auto-populate an array with a seed value that's not the default? Either on creation or a built-in method afterwards (like Java's Arrays.fill())? 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 似乎效率低下.有没有办法解决?也许通过翻转所有值?

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天全站免登陆