【问题标题】:Declare a List of fixed size array声明一个固定大小数组的列表
【发布时间】: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;
    }

【问题讨论】:

  • 可以帮到你的问题stackoverflow.com/questions/466946/…
  • 创建一个包含 int 数组的类(比如class ArrayOf2Int)。使类表现得像一个数组(大部分),但将其限制为只有两个整数。您可能会发现让它包含两个整数更容易。不管你做什么,给它一个尽可能接近int[]的类型签名

标签: c#


【解决方案1】:

这是不可能的,参考this post,简而言之,int[2] 不是Type,因此没有结构、模型或元组就无法限制它。

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

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

【讨论】:

  • 注意 OP,ValueTuple is 结构体,与使用数组相反,每次使用或更新时都会复制和创建它们它们并具有任何其他值类型的所有微妙之处(可能会或可能不会让您担心)...
【解决方案2】:

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

无论如何,它都会让您了解可能的解决方案:

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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多