我有一个在下面声明的列表,在开始时我将列表项默认为 { -1, - }。请注意,在整个程序中,列表大小固定为 2。
List<int> list = new List<int>(new int[] {-1, -1});
我的问题是,如果我需要覆盖列表中的两个值,最好的方法是什么。
int x = GetXValue();
int y = GetYValue();
方法一:
list = new List<int>(new int[] {x, y});
方法 2:
list[0] = x;
list[1] = y;
什么是更好的方法?使用第二种方法,即使我确定最初设置了 2 个值,我也可能会遇到 Argument index out of range
异常的风险。但是第一种方法可能会占用更多内存(如果我错了请纠正我!)因为我每次都在创建一个新列表。
是否有更简单和/或更好的解决方案
最佳答案
Or is there a simpler and better solution?
是的。由于列表具有固定大小,因此请使用真实对象,例如 System.Drawing.Point :
Point p = new Point(1, -1);
p = new Point(5, 10);
Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);
关于c# - .NET 列表最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3481064/