[英]Creating an array of objects from a class in C#
我正在尝试从我的Candidate
类中创建20个候选数组。 到目前为止,这就是我所拥有的:
Candidate candidate0 = new Candidate();
Candidate candidate1 = new Candidate();
Candidate candidate2 = new Candidate();
Candidate candidate3 = new Candidate();
...
Candidate candidate19 = new Candidate();
Candidate[] candidates = new Candidate[20];
candidates[0] = candidate0;
candidates[1] = candidate1;
candidates[2] = candidate2;
candidates[3] = candidate3;
...
candidates[19] = candidate19;
我知道这不是正确的或“最佳”方法。 最好的方法是什么?
您需要的是for循环 :
int candidateLength = 20 ;
Candidate[] candidates = new Candidate[candidateLength ];
for(int i=0 ; i<candidates.Length ; i++)
{
candidates[i] = new Candidate();
}
亚当-在主观上,最好使用以下列表:
List<Candidate> canditateList = new List<Candidate>();
// MaxLength is a const defined somewhere earlier perhaps
for(int i=0 ;i<MaxLength;i++){
canditateList.Add(new Candidate(){... properties here});
}
// etc, etc.
然后,如果需要,可以使用以下方法将其分解为一个数组:
var candidateArray = canditateList.ToArray();
只是我最初的想法,当然您可能有充分的理由希望从一开始就使用数组,我的前提是我会列出并列出各种提取的口味。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.