【问题标题】:Why tuple type is not accepted as a multidimensional array index?为什么元组类型不被接受为多维数组索引?
【发布时间】:2018-11-24 01:18:00
【问题描述】:

我想知道为什么这不能按我预期的方式工作。这只是“运送就是选择”的问题,还是有一个很好的实际理由,我所期望的行为是有问题的。

考虑这个变量定义:

int[,] a

还有这个函数签名

(int, int) FindIndex(int[,] a)

鉴于这些,我希望这会起作用:

int index = a[FindIndex(a)];

但它没有,它给出:

CS0022 [] 内的索引数量错误;预计 2

我没有检查规范,但我确信这符合规范,所以我不质疑实现是否正确,肯定是。我想知道的是,是否有任何实际原因和/或考虑不支持此功能?

【问题讨论】:

标签: c#


【解决方案1】:

将元组作为索引器的完全无意义的类

public class MyFunkyArray<T> : IEnumerable<T>
{
    public MyFunkyArray() { }

    public MyFunkyArray(T[,] buffer) => Buffer = buffer;

    public T[,] Buffer { get; set; }

    public T this[(int, int) tuple]
    {
        get => Buffer[tuple.Item1, tuple.Item2];
        set => Buffer[tuple.Item1, tuple.Item2] = value;
    }

    public IEnumerator<T> GetEnumerator() => ToEnumerable(Buffer).GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

    public IEnumerable<T> ToEnumerable(Array target) => target.Cast<T>();
}

用法

var array = new MyFunkyArray<int>(new int[2, 2]);

var tuple = (1, 1);

array[tuple] = 3;

foreach (var val in array)
    Console.WriteLine(val);

输出

0
0
0
3

注意:这真的只是为了学术目的,价值有限


其他资源

Indexers (C# Programming Guide)

索引器允许类或结构的实例被索引,就像 数组。无需显式设置或检索索引值 指定类型或实例成员。索引器类似于属性 除了它们的访问器带参数。

【讨论】:

    猜你喜欢
    • 2012-08-29
    • 1970-01-01
    • 2021-11-05
    • 2011-02-22
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多