次のように、オーバーロードされたインデクサーを持つ 2 次元の Matrix クラスを考えてみましょう。
public class Matrix
{
private readonly double[,] _matrix;
public double this[int i, int j]
{
get
{
return _matrix[i, j];
}
set
{
_matrix[i, j] = value;
}
}
public double this[int i, int j]
{
get
{
if (i < 0 || i >= _matrix.GetLength(0) || j < 0 || j >= _matrix.GetLength(1))
throw new IndexOutOfRangeException("index was out of range");
return _matrix[i, j];
}
set
{
if (i < 0 || i >= _matrix.GetLength(0) || j < 0 || j >= _matrix.GetLength(1))
throw new IndexOutOfRangeException("index was out of range");
_matrix[i, j] = value;
}
}
public double this[int i, int j]
{
get
{
if (i < 0 || i >= _matrix.GetLength(0) || j < 0 || j >= _matrix.GetLength(1))
return 0;
return _matrix[i, j];
}
set
{
if (i >= 0 || i < _matrix.GetLength(0) || j >= 0 || j < _matrix.GetLength(1))
_matrix[i, j] = value;
}
}
}
ご覧のとおり、インデクサーには 3 つのバージョンがあります。
1) このバージョンはインデックスをチェックしません
2) このバージョンはインデックスをチェックし、サイズを超えている場合は IndexOutOfRangeException をスローします。
3) このバージョンはインデックスをチェックし、インデックスが有効な場合にのみ値を割り当て/返します。
だから私の質問は、それらのどれを使用するのがベストプラクティスですか? あなたは何を好みますか、そしてその理由は何ですか? または、「MatrixIndexOutOfRange」のような新しいカスタム例外を作成して、IndexOutOfRange 例外の代わりにスローすることはできますか?