gpt4 book ai didi

c# - .NET 列表最佳方法

转载 作者:太空狗 更新时间:2023-10-29 19:59:04 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com