我正在尝试为索引器编写自定义重载。目前我有一个二维数组定义如下:
private float[][] Values;
现在我想像这样为我的自定义结构进行重载,但这无法编译..
float this[int x][int y] { get; set; }
我发现可以通过以下方式做到这一点:
private float[,] Values;
像这样过载:
float this[int x, int y] { get; set; }
但是我更喜欢
[][]
语法,而不是 [x, y]
语法,有没有办法创建我正在寻找的重载类型?
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];
}