简短的回答是不,你不能在本地做到这一点。
略长一点的答案是肯定的,您可以使用扩展方法来实现这样的行为。您可以添加一个适用于所有数组的扩展方法,如下所示:
public static class ArrayExtender
{
public static T GetValue<T>(this T[,] array, params int[] indices)
{
return (T)array.GetValue(indices);
}
public static void SetValue<T>(this T[,] array, T value, params int[] indices)
{
array.SetValue(value, indices);
}
public static T ExchangeValue<T>(this T[,] array, T value, params int[] indices)
{
var previousValue = GetValue(array, indices);
array.SetValue(value, indices);
return previousValue;
}
}
你可以使用:
var matrix = new int[3, 3];
matrix[0, 2] = 99;
var oldValue = matrix.GetValue(0, 2);
matrix.SetValue(100, 0, 2);
var newValue = matrix.GetValue(0, 2);
Console.WriteLine("Old Value = {0}", oldValue);
Console.WriteLine("New Value = {0}", newValue);
输出:
Old Value = 99
New Value = 100
在大多数情况下,有一个面向对象的答案来解释您为什么需要此功能,并且可以创建适当的自定义类来促进这一点。例如,我可能有一个棋盘,我用辅助方法创建了几个类:
class GameBoard
{
public GamePiece GetPieceAtLocation(Point location) { ... }
}