我正在尝试创建一个空的数组点,因为我正在使用以下内容
Point[] listapontos = new[]; //should create a empty point array for later use but doesn't.
Point ponto = new Point(); //a no coordinates point for later use
for (int i = 1; i <= 100; i++) //cycle that would create 100 points, with X and Y coordinates
{
ponto.X = i * 2 + 20;
ponto.Y = 20;
listapontos[i] = ponto;
}
Run Code Online (Sandbox Code Playgroud)
我遇到了一些麻烦,因为我无法创建一个空的点数组.我可以使用列表创建一个空的字符串数组,但由于我需要两个元素,因此列表在这里没用.
任何提示?(也欢迎提出问题的提示)
//应该创建一个空点数组供以后使用,但不能.
不,你刚刚指定的是无效的语法.如果你想要一个空数组,你可以使用以下任何一个:
Point[] listapontos = new Point[0];
Point[] listapontos = new Point[] {};
Point[] listapontos = {};
Run Code Online (Sandbox Code Playgroud)
但是,你有一个包含0个元素的数组,所以这个声明:
listapontos[i] = ponto;
Run Code Online (Sandbox Code Playgroud)
...然后会抛出异常.听起来你应该使用a List<Point>,或创建一个101大小的数组:
Point[] listapontos = new Point[101];
Run Code Online (Sandbox Code Playgroud)
(或者创建一个大小为100的数组,并更改您使用的索引 - 目前您没有为索引0分配任何内容.)
重要的是要理解在.NET中,数组对象在创建后不会改变其大小.这就是为什么它通常很方便使用List<T>,包装一个数组,"调整大小"(通过创建一个新的数组和复制值),当它需要时.
| 归档时间: |
|
| 查看次数: |
885 次 |
| 最近记录: |