重载索引器样式 [][] 与 [x,y]

问题描述 投票:0回答:1

我正在尝试为索引器编写自定义重载。目前我有一个二维数组定义如下:

private float[][] Values;

现在我想像这样为我的自定义结构进行重载,但这无法编译..

float this[int x][int y] { get; set; }

我发现可以通过以下方式做到这一点:

private float[,] Values;

像这样过载:

float this[int x, int y] { get; set; }

但是我更喜欢

[][]
语法,而不是
[x, y]
语法,有没有办法创建我正在寻找的重载类型?

c# overloading indexer
1个回答
0
投票

DotNetFiddle 示例

using System;
using System.Linq;
using SCG = System.Collections.Generic;

var Indexer = new Indexer<float>
{
    Payload = [
        [float.Epsilon, float.Epsilon, float.Epsilon],
        [float.Epsilon, float.Pi, float.Epsilon],
        [float.Epsilon, float.Epsilon, float.Epsilon],
    ]
};
Console.WriteLine(Indexer[1][1]); // Output: 3.1415927
Console.WriteLine(Indexer[1, 1]); // Output: 3.1415927

public class Indexer<T> {
    public Indexer() => Payload = [[]];
    public SCG.IEnumerable<SCG.IEnumerable<T>> Payload { get; init; }

    public T[] this[int row] {
        get => Payload.ValueAt(row).ToArray();
    }
    public T this[int row, int col] {
        get => this[row].ValueAt(col);
    }
}
internal static class Extension {
    internal static T ValueAt<T>(this SCG.IEnumerable<T> collection, int index)
        => collection.ToArray()[index];
}
© www.soinside.com 2019 - 2024. All rights reserved.