gpt4 book ai didi

c# - 带有 2 个参数的列表

转载 作者:太空狗 更新时间:2023-10-29 23:06:33 25 4
gpt4 key购买 nike

我目前有这段代码:

List<int> list = new List<int>();
list.Add(0);
list.Add(1);
list.Add(2);
list.Add(3);
color0 = list[1];
color1 = list[2];
color2 = list[3];
color3 = list[4];

有没有一种可能的方法,这个列表可以在 1 个元素中包含 2 个参数?我的意思是:

List<int,int> list = new List<int,int>();
list.Add(0,3);
list.Add(1,8);
color0=list[1][2]; //output 3
color1=list[1][1]; //output 0
color2=list[2][2]; //output 8
color3=list[2][1]; //output 1

有没有可能我可以实现类似的东西?

最佳答案

你可以使用元组:

var list = new List<Tuple<int, int>>();
list.Add(new Tuple<int, int>(1, 2));

为了更容易使用,您可以创建一个扩展方法:

public static class Extensions
{
public static void Add(this List<Tuple<int, int>> list, int x, int y)
{
list.Add(new Tuple<int, int>(x, y));
}
}

然后您可以使用此代码添加一个元素:

list.Add(1, 2);

访问项目:

var listItem = list[0]; // first item of list
int value = listItem.Item2; // second "column" of the item

关于c# - 带有 2 个参数的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31762299/

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