我创建了一个自定义结构和一个类。结构是 3D 空间中的点:
public struct Point3D
{
//fields
private static Point3D center = new Point3D(0,0,0);
//properties
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public static Point3D Center { get { return center; } }
//constructors
public Point3D(int x, int y, int z) : this()
{
this.X = x;
this.Y = y;
this.Z = z;
}
public override string ToString() { return string.Format("({0}; {1}; {2})", this.X, this.Y, this.Z); }
}
并且自定义类是应该存储点的路径:
public class Path
{
private List<Point3D> storedPoints = new List<Point3D>();
public List<Point3D> StoredPoints { get; set; }
public void AddPoint(Point3D point) { this.StoredPoints.Add(point); }
public void DeletePointAt(int index) { this.StoredPoints.RemoveAt(index); }
public void ClearPath() { this.StoredPoints.Clear(); }
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this.StoredPoints)
{
sb.Append(item);
sb.Append(System.Environment.NewLine);
}
return sb.ToString();
}
}
我没有为路径类创建构造函数,因为我总是希望有一个实例,其中包含一个空列表 List\。但是,当我运行程序时,我得到 NullReferenceException。这是主要方法的代码:
static void Main(string[] args)
{
Point3D point1 = new Point3D(-2, -4, -10);
Point3D point2 = new Point3D(6, 7, 8);
Path path1 = new Path();
path1.AddPoint(point1);
path1.AddPoint(point2);
path1.AddPoint(new Point3D(2, 4, 6));
path1.AddPoint(new Point3D(-9, 12, 6));
Console.WriteLine(path1);
}
当我尝试添加第一点时出现错误。在调试器中,我看到 Path 对象在添加第一个点之前的值为 null,但是如何在无需编写构造函数的情况下克服这个问题,将至少一个点作为参数,即创建一个空路径。