c# - .NET 列表最佳方法

标签 c# .net list collections

我有一个在下面声明的列表,在开始时我将列表项默认为 { -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/

相关文章:

string - 如何在 Netlogo 中逐行导入 CSV?

c# - 如何在两个动态生成的组合框上使用不同的值

c# - 如何创建一个总是产生的任务?

c# - 如何在不使用WMI的情况下获取拥有进程的用户名?

c# - 如何通过 C# 使用 CryptoAPI?

Java : add elements in linked list incrementally

使用 foreach 循环的 C# List 或 Collection 初始值设定项

c# - 新手 caSTLe windsor 并尝试创建我的接口(interface)的实现

c# - 在循环中创建新对象

c# - HTML.DropDownListFor DropDownList