我在C#中编写一个Vector类,并觉得索引器会是一个很好的补充。我是否需要担心索引超出范围?使用C#索引器时的索引安全性?
也许代码示例会更清楚:
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;
}
}
}
}
我应该把default
情况下,我switch
报表?它应该做什么?
编辑:这是一个相当愚蠢的问题。如果没有default
的情况,上面的代码甚至不会编译。再加上杰森在下面的实施非常棒。
这很漂亮。 – Anton 2009-12-02 02:37:39
如果需要,索引器可以更容易地遍历Vector的坐标。 – mkenyon 2009-12-02 02:38:57
伟大的实施。 – Alex 2009-12-02 02:39:13