我正在用C#编写一个Vector类,并认为索引器是一个很好的补充.我是否需要担心指数超出范围?
也许代码示例会更清晰:
class Vector3f
{
public Vector3f(float x, float y, float z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public float X {get; set;}
public float Y {get; set;}
public float Z {get; set;}
public float this[int pos]
{
get
{
switch (pos)
{
case 0: return this.X; break;
case 1: return this.Y; break;
case 2: return this.Z; break;
}
}
set
{
switch (pos)
{
case 0: this.X = value; break;
case 1: this.Y = value; break;
case 2: this.Z = value; break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该default
在我的switch
陈述中加上案例吗?它该怎么办?
编辑:这是一个相当愚蠢的问题.如果没有这个default
案例,上面的代码甚至都不会编译.加上杰森在下面的实施是一流的.
这更加清晰,并且无需担心范围检查:
public enum Coordinate { X, Y, Z }
public float this[Coordinate coordinate] {
get {
switch(coordinate) {
case Coordinate.X: return this.X;
case Coordinate.Y: return this.Y;
case Coordinate.Z: return this.Z;
// convince the compiler that we covered everything
default: throw new ArgumentOutOfRangeException("coordinate");
}
}
set {
switch(coordinate) {
case Coordinate.X: this.X = value; break;
case Coordinate.Y: this.Y = value; break;
case Coordinate.Z: this.Z = value; break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但请注意,坐标已经公开,那么索引器的重点是什么?