类对象列表内的点列表[关闭]

问题描述 投票:0回答:3

这是类定义的片段:

 public class Dinosaur
{
    public string Specie { get; set; }
    public int Age { get; set; }
    public List<System.Windows.Point> Location { get; set; }

    // Constructor
    public Dinosaur()
    {

    }
}

现在我们创建一个列表:

        public static List<Dinosaur> Dinosaurs = new List<Dinosaur>();

现在我们要创建并添加点列表。

 List<System.Windows.Point> Location = new List<System.Windows.Point>();

            for (int y = (int)pt.Y - 5; y <= (int)pt.Y + 5; y++)
                for (int x = (int)pt.X - 5; x <= (int)pt.X + 5; x++)
                    Location.Add (new System.Windows.Point (x, y ));

            Dinosaurs.Last().Location.AddRange(Location); 

最后一行抛出空指针异常。这很奇怪,因为位置有 121 个好的值。

有什么想法吗?

c# list class point
3个回答
1
投票

您的列表

Location
不应该是静态的,因为您正在调用 Last() 方法。

public class Dinosaur
        {
            public string Specie { get; set; }
            public int Age { get; set; }
            public List<System.Windows.Point> Location { get; set; } // this shouldn't be static

            // Constructor
            public Dinosaur()
            {

            }
        }

    public static List<Dinosaur> Dinosaurs = new List<Dinosaur>(); // your list of dinosaurs somewhere

    List<System.Windows.Point> yourListOfPoints = new List<System.Windows.Point>(); // create a new list of points to add
    yourListOfPoints.Add(new Point { X = pixelMousePositionX, Y = oldLocation.Y }); // add some points to list
    Dinosaurs.Last().Location.AddRange(yourListOfPoints); // select last dinosaur from list and assign your list of points to it's location property

编辑

在实际使用它之前,您必须在构造函数中创建一个列表:

public List<System.Windows.Point> Location { get; set; }

// Constructor
public Dinosaur()
{
    Location = new List<System.Windows.Points>();
}

或更换:

Dinosaurs.Last().Location.AddRange(Location); 

与:

Dinosaurs.Last().Location = Location; 

1
投票
var points =
    from d in Dinosaurs
    select d.Location;

根据您的问题,我不确定这是否是您所要求的。

编辑: 好的,我可能会在 Dinosaur 类的构造函数中设置 List。然后我想在其中添加一系列点,我就会有这个代码。

IEnumerable<Point> points = getPointsFromSomewhere();
myDinosaurObject.Location.AddRange(points);

1
投票

假设问题是关于

List<Point> Locations
的初始化或补充,除了上述内容(尽管我不认为在这种情况下更好),您可以使用 集合初始化器:

List<Point> Locations = new List<Point>()
        {
            new Point(1, 2),
            new Point(3, 4),
            new Point(5, 6),
            new Point(1, 1)
        };

不过我会选择

AddRange
选项。

© www.soinside.com 2019 - 2024. All rights reserved.