繁体   English   中英

声明一个固定大小数组的列表

[英]Declare a List of fixed size array

我想确保我的 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[2]不是Type ,因此没有结构 model 或元组就无法限制它。

在这种情况下,我更喜欢使用元组,因为 lambda 非常简单

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

这是一个固定长度数组的想法。 如果长度超过 2,那么我可能会有一个private int[] theArray成员。 但是,在两个时,以我展示的方式拥有一个_first和一个_second成员可能是有意义的。 System.Array class 有很多成员——你可以实现你关心的那些(我把所有的属性都放进去(作为一个属性或一个const ))。

在任何情况下,它都会让您了解可能的解决方案:

public class ArrayOf2Int : IEnumerable<int>
{
    private readonly int _first;
    private readonly int _second;

    //I had the urge to make this a Lazy<object> - but it's an object, who cares
    //If you implement this with an array of int (int[]) instead of two ints, delegate this to the SyncRoot of the array
    public object SyncRoot { get; } = new object();

    public const int Length = 2;
    public const long LongLength = 2;
    public const int Rank = 1;
    public const bool IsFixedSize = true;
    public const bool IsSynchronized = false;

    public ArrayOf2Int(int first, int second)
    {
        _first = first;
        _second = second;
    }

    public int this[int i]
    {
        get
        {
            if (i < 0 || i > 1)
            {
                throw new ArgumentOutOfRangeException(nameof(i), "Index out of range");
            }

            return i == 0 ? _first : _second;
        }
    }
    public IEnumerator<int> GetEnumerator()
    {
        yield return _first;
        yield return _second;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM