【发布时间】:2020-12-17 03:08:27
【问题描述】:
我想确保我的 List 只能包含 2 个 int 元素数组。我目前必须声明一个结构,但如果不是真的有必要,我真的不想声明许多类型。所以我想知道我是否可以声明一个固定大小数组的列表。
static void Main(string[] args)
{
//I want to declare something like this
List<int[2]> list = new List<int[2]>();
list.Add(new int[2] { 1, 2 });
list.Add(new int[2] { 3, 4 });
//What I having to do(not really want because I have to declare struct)
List<TwoElement> list2 = new List<TwoElement>();
list2.Add(new TwoElement() { Element1 = 1, Element2 = 2 });
list2.Add(new TwoElement() { Element1 = 1, Element2 = 2 });
}
private struct TwoElement
{
public int Element1;
public int Element2;
}
【问题讨论】:
-
创建一个包含 int 数组的类(比如
class ArrayOf2Int)。使类表现得像一个数组(大部分),但将其限制为只有两个整数。您可能会发现让它包含两个整数更容易。不管你做什么,给它一个尽可能接近int[]的类型签名
标签: c#