[英].NET List best approach
我有一個列表,在下面聲明,在開始時我將列表項默認為{-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
異常的風險。 但是第一種方法可能會占用更多內存(如果我錯了,請糾正我!)因為我每次都會創建一個新列表。
是否有更簡單和/或更好的解決方案
或者是否有更簡單,更好的解決方案?
是。 由於列表具有固定大小,因此請使用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;
}
}
為什么不是自定義類,特別是因為它是一個固定的大小。
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();
}
}
結構也可以工作
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;
方法2會更好,因為方法1會導致不必要的內存分配(創建新列表和數組等)
但是,您的列表中只有2個項目的事實使我認為列表是您的方案中使用的錯誤類。
也許我不了解你的情況,但我認為一個更好的解決方案是一個簡單的數組?
int[] list = new int[] { -1, 1 };
我建議你使用一個數組,這意味着集合保持固定的大小,第二種方法來訪問它。 所以:
int[] array = new[] { -1, -1 };
然后改變它:
array[0] = x;
array[1] = y;
由於數組不會更改大小,並且為其分配了2個值,因此不會獲得IndexOutOfRangeException
。 我通常不會使用第一種方法來更改集合的內容 - 通常,更改現有對象比創建新對象更好。
另外,您可以為List<T>
編寫初始化程序,如:
new List<int> {-1, -1};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.