您可以实现自己的矩阵类型来存储实际索引
public class Matrix<T>
{
private T[, ,] _array;
public Matrix(int sizeX, int sizeY, int sizeZ)
{
_array = new T[sizeX, sizeY, sizeZ];
}
public T this[int i, int j, int k]
{
get { return _array[i, j, k]; }
set { _array[i, j, k] = value; }
}
public int CurrentI { get; set; }
public int CurrentJ { get; set; }
public int CurrentK { get; set; }
public void SetCurrentCell(int i, int j, int k)
{
CurrentI = i;
CurrentJ = j;
CurrentK = k;
}
public T Current
{
get { return _array[CurrentI, CurrentJ, CurrentK]; }
set { _array[CurrentI, CurrentJ, CurrentK] = value; }
}
public static implicit operator T(Matrix<T> matrix)
{
return matrix.Current;
}
// The assignment operator (=) cannot be overloaded. But we can overload |
// instead, allowing us to write: m |= value in order to perform an assignment.
public static Matrix<T> operator |(Matrix<T> m, T value)
{
m.Current = value;
return m;
}
}
你可以像这样使用它:
var m = new Matrix<int>(3, 3, 3);
m[0, 2, 1] = 77;
m.SetCurrentCell(0, 2, 1);
m.Current = 88;
int value = m; // Using the implicit operator and the current indexes
m |= 20; // Using |= as assignment operator
泛型方法的缺点是实现数字运算变得更加困难(诸如 +、-、*、/ 之类的数学运算未在泛型类型上定义)。但是您可以在实现数值计算的派生类中解析泛型类型
public class DoubleMatrix : Matrix<double> {
public static DoubleMatrix operator +(DoubleMatrix a, DoubleMatrix b)
{
//TODO: Implement + operator
return m;
}
//TODO: Implement other operators
}
C# 7.0 引入了 ref locals 允许您这样做
ref int xx = ref myArray[i, j, k];
if (xx == someValue)
xx = someOtherValue;
else
throw new Exception(string.Format("value {0} is wrong!", xx));
请注意,您不仅获得同义词,而且获得引用,这意味着数组索引仅被评估一次。