如何使用运行时确定的尺寸来初始化 C# 数组?
感谢您的关注。
我有一个 2D c# 数组,其维度之一为 50。另一个维度取决于数据库中某处的行数,并在运行时决定。我将如何初始化这样的数组?
目前我对单行的初始化看起来像这样,但我确信有更好的方法来做到这一点,更有效:)
temp = new Double[50,1] { {0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},
{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},
{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}};
and thanks for looking.
I have a 2D c# array, that has 50 as one of its dimensions. The other dimension depends on the number of rows in a database somewhere and is decided at runtime. How would I go about initializing an array like this?
Currently my initialization for a single row looks like this, but I'm sure there's a better way to do it, more efficiently :)
temp = new Double[50,1] { {0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},
{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},
{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需在运行时使用第二维的整数变量初始化数组即可。
C# 会自动将所有双精度数初始化为零,因此在您的特定情况下,您不需要显式初始化这些值。
Simply initialize the array at runtime using an integer variable for the second dimension.
C# will automatically initialize all doubles to zero, so in your specific circumstance, you don't need to explicitly initialize the values.
正如托比所说,您不需要显式地将
double
值设置为零,因为default(double) == 0.0
。但是,如果您想将数组的所有成员初始化为数组类型默认值之外的某个值,您始终可以这样做:
这将允许您编写如下代码:
As Toby said, you don't need to explicity set
double
values to zero sincedefault(double) == 0.0
.However, if you want to initialize all members of an array to some value other than the default for the array's type, you could always do this:
This would allow you to write code such as this:
如果数组的第二个维度可以变化,请使用锯齿状数组
知道您设置的数组暗淡的确切大小。
如果它始终具有矩形大小,请使用以下构造
If a second dim of array can vary use jagged array
When you will know exact size of array dim you set it with.
If it always has rectangular size use following construct
有关数组的详细信息,请查看此处 。
Take a look here for more information about arrays.