如何初始化自定义类型数组 [英] How to Initialize Array with Custom Type

查看:137
本文介绍了如何初始化自定义类型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何初始化数组自定义类型的:

How do I initialize this array of custom types:

PostType[] q = new PostType[qArray.Length];

//initialize array
for( int x = 0; x < qArray.Length; x++)
    q[x] = new PostType();

有没有更好的方法来初始化数组?

Is there a better way to initialize this array?

推荐答案

你正在做它的方式是好的:

The way you are doing it is fine:

PostType[] q = new PostType[qArray.Length];
for (int i = 0; i < q.Length; i++)
    q[i] = new PostType();

有一件事情我已经改变了对veriable重命名该指数从x到我,因为我觉得这更容易阅读,虽然这是一个主观的东西。

One thing I have changed are to rename the index veriable from x to i, as I find this easier to read, although it's a subjective thing.

我已经改变了另一件事是在for循环结束条件应该取决于q的长度,而不是qArray的长度。这样做的原因是,与你的方法,如果你决定改变使用不同的长度,而不是qArray.Length的第一行,你必须记得更改第二行了。随着修改code,你只需要更新code的第一行,其余的将而无需修改。

Another thing I have changed is the for loop end condition should depend on the length of q, not on the length of qArray. The reason for this is that with your method if you decide to change the first line to use a different length instead of qArray.Length, you'd have to remember to change the second line too. With the modified code you only need to update the first line of code and the rest will work without modification.

您也可以做到这一点使用LINQ:

You could also do this using Linq:

PostType[] q = Enumerable.Range(0, qArray.Length)
                         .Select(_ => new PostType())
                         .ToArray();

但对于大数组这会慢一些,并没有真正容易在我看来,阅读(特别是如果你以前没有见过吧)。我想我大概只是​​坚持与第一种方法,如果我是你。

But for large arrays this will be slower and not really easier to read in my opinion (especially if you haven't seen it before). I think I'd probably just stick with the first method if I were you.

这篇关于如何初始化自定义类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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