Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c# - Why tuple type is not accepted as a multidimensional array index?

I'm wondering why this is not working the way I expect it to work. Is this just the matter of "to ship is to choose" or is there a good practical reason, that the behaviour I'm expecting is problematic.

Consider this variable definition:

int[,] a

And this function signature

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

Given these I would expect this to work:

int index = a[FindIndex(a)];

But it does not, it gives:

CS0022 Wrong number of indices inside []; expected 2

I did not check the spec, but I'm sure that this is in accordance with spec, so I do not question if the implementation is correct, it surely is. What I would like to know, are there any practical reasons and/or considerations for this not to be supported?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Totally nonsensical class to take tuples as an indexer

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

Usage

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

var tuple = (1, 1);

array[tuple] = 3;

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

Output

0
0
0
3

Note : this is really only for academic purposes, and has limited value


Additional Resources

Indexers (C# Programming Guide)

Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...