C#List< GenericClass>(100)构造原理 [英] C# List<GenericClass>(100) Construction Principles

查看:165
本文介绍了C#List< GenericClass>(100)构造原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我执行以下操作:

List<GenericClass> listObj = new List<GenericClass>(100);

// Do I need this part too?
for (int i = 0; i < 100; i++)
{
    listObj[i] = new GenericClass();
}

基本上,我问的是C#编译器是否会自动激发GenericClass构造函数的100个GenericClass对象。我在MSDN文档中搜索以及在StackOverflow上搜索。

Basically I am asking if the C# compiler will automatically fire the GenericClass constructor for each of the 100 GenericClass objects in the list. I searched in the MSDN documentation as well as here on StackOverflow.

感谢任何帮助。

推荐答案

这不是 List 如何工作。指定容量时,它是一个初始容量,而不是列表中的项目数。该列表不包含任何元素,直到您通过添加方法添加它们。列表没有最大容量。因为你是通过Add方法添加对象,是的,你必须先新建它们。

That's not how List works. When you specify a capacity, it's an initial capacity, not the number of items in the list. The list contains no elements until you add them via the Add method. Lists do not have a maximum capacity. And since you're adding objects via the Add method, yes, you would have to new them up first.

事实上,做你的问题会抛出 ArgumentOutOfRange 异常。

In fact, doing what you put in your question would throw an ArgumentOutOfRange exception.

对于你正在做的,你需要使用一个数组。 p>

For what you're doing, you'd need to use an array.

var listObj = new List<GenericClass>();
listObj[0] = new GenericClass(); // ArgumentOutOfRange exception

这将工作:

for (int i=0;i<100;i++)
{
    listObj.Add(new GenericClass());
}

这是您尝试执行的操作:

This is what you were attempting to do:

var arrayObj = new GenericClass[100];
for (int i = 0; i < 100; i++)
{
    arrayObj[i] = new GenericClass();                
}

这篇关于C#List&lt; GenericClass&gt;(100)构造原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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