我有一个在下面声明的列表,在开始时我将列表项默认为{-1, - }。请注意,在整个计划中,列表大小固定为2。
List<int> list = new List<int>(new int[] {-1, -1});
我的问题是,如果我需要覆盖列表中的两个值,那么最好的方法是什么。
int x = GetXValue();
int y = GetYValue();
方法1:
list = new List<int>(new int[] {x, y});
方法2:
list[0] = x;
list[1] = y;
什么是更好的方法?使用第二种方法,即使我确定最初设置了2个值,但我可能会遇到Argument index out of range
异常的风险。但是第一种方法可能会占用更多内存(如果我错了,请纠正我!)因为我每次都会创建一个新列表。
是否有更简单和/或更好的解决方案
答案 0 :(得分:12)
或者是否更简单,更好 溶液
是。由于列表具有固定大小,因此请使用真实对象,例如System.Drawing.Point:
Point p = new Point(1, -1);
p = new Point(5, 10);
Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);
答案 1 :(得分:1)
这看起来好像要封装,这会消除使用网站的复杂性。
封装应提供所有行为,包括从-1, -1
开始并同时设置X
和Y
。你可以这样做:
public class ItemSet
{
public ItemSet()
{
this.X = -1;
this.Y = -1;
}
public int X { get; private set; }
public int Y { get; private set; }
public void SetItems(int x, int y)
{
this.X = x;
this.Y = y;
}
}
答案 2 :(得分:1)
为什么不是自定义类,特别是因为它是固定大小。
class MyClass {
public MyClass(int x, int y) {
}
public int X { get; set; }
public int Y { get; set; }
public int[] ToArray() {
return new[] { X, Y };
}
public List<int> ToList() {
return ToArray().ToList();
}
}
答案 3 :(得分:1)
结构也可以起作用
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y):this()
{
this.X = x;
this.Y = y;
}
}
Point p = new Point(-1, -1);
// ...
p.X = newX;
p.Y = newY;
答案 4 :(得分:1)
方法2会更好,因为方法1会导致不必要的内存分配(创建新的列表和数组等)。
但是,您的列表中只有2个项目,这使我认为列表是您的方案中使用的错误类。
答案 5 :(得分:0)
也许我不了解你的情况,但我认为更好的解决方案是一个简单的数组?
int[] list = new int[] { -1, 1 };
答案 6 :(得分:0)
我建议您使用数组,这意味着集合保持固定大小,第二种方法是访问它。所以:
int[] array = new[] { -1, -1 };
然后改变它:
array[0] = x;
array[1] = y;
由于数组不会更改大小,并且为其分配了2个值,因此您将无法获得IndexOutOfRangeException
。我通常不会使用第一种方法来更改集合的内容 - 通常,更改现有对象比创建和新对象更好。
除此之外,您可以为List<T>
编写初始化内容,例如:
new List<int> {-1, -1};