C# 如何初始化一个Point数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15388079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:37:51  来源:igfitidea点击:

How to initialize an array of Point?

c#arraysconstructorinitializationpoint

提问by Mixer

I need to initialize an array of three points. I want to write it like below, but only once for three elements.

我需要初始化一个由三个点组成的数组。我想像下面那样写它,但对于三个元素只写一次。

Point P = new Point { X = 0, Y = 1 };

Point[] P = new Point[3];// <----  ?

How to write correctly?

如何正确书写?

采纳答案by Marek Musielak

Here is the code for creating the array of 3 different points:

这是用于创建 3 个不同点的数组的代码:

Point[] points = new Point[] { new Point { X = 0, Y = 1 }, new Point { X = 2, Y = 1 }, new Point { X = 0, Y = 3 } };

回答by Ry-

There's not really a shorthand for that. For three, just write it three times:

没有真正的简写。对于三个,只需写三遍:

Point initial = new Point { X = 0, Y = 1 };
Point[] P = new Point[3] { initial, initial, initial };

回答by Larry

Because you question deals about a static fixed length array of point with static coordinates, no needs to bother with LINQ and loops in this context when array initialization is that simple.

因为您对具有静态坐标的点的静态固定长度数组有疑问,所以当数组初始化如此简单时,无需在此上下文中理会 LINQ 和循环。

So you can initialize an array this way:

所以你可以这样初始化一个数组:

Point[] P = new Point[] 
{ 
    new Point { X = 0, Y = 1 }, 
    new Point { X = 0, Y = 1 }, 
    new Point { X = 0, Y = 1 },
    ...
};

or use duck typingtype inference (thanks minitech):

或使用鸭子类型推断(感谢minitech):

var P = new [] 
{ 
    new Point { X = 0, Y = 1 }, 
    new Point { X = 0, Y = 1 }, 
    new Point { X = 0, Y = 1 },
    ...
};

回答by cuongle

Example below you can create 10 Pointusing Enumerable.Range

下面的示例您可以Point使用创建 10Enumerable.Range

var points = Enumerable.Range(0, 10)
            .Select(x => new Point {X = 0, Y = 1})
            .ToArray();

回答by platon

Here is the shortest solution:

这是最短的解决方案:

Point[] points = Enumerable.Repeat<Point>(new Point(0, 1), 3).ToArray();