使用C#索引器时的索引安全性?

mke*_*yon 0 c#

我正在用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案例,上面的代码甚至都不会编译.加上杰森在下面的实施是一流的.

jas*_*son 7

这更加清晰,并且无需担心范围检查:

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)

但请注意,坐标已经公开,那么索引器的重点是什么?