[英]Index safety when using C# indexers?
我正在用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;
}
}
}
}
我應該在switch
語句中放入default
案例嗎? 應該怎么辦?
編輯:這是一個相當愚蠢的問題。 沒有default
情況,上面的代碼甚至無法編譯。 另外,Jason在下面的實現非常出色。
這更加清楚,不需要擔心范圍檢查:
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;
}
}
}
但是請注意,坐標已經公開,所以索引器的作用是什么?
我認為您應該像其他容器(例如List)一樣拋出ArgumentOutOfRangeException。 您可以從默認情況下拋出它。
也許您應該為此使用枚舉而不是int索引器,這樣,您的代碼將更加清晰,並且您不必擔心超出范圍的異常。 實際上,這使人們很難看到代碼的意圖。
無論如何,您都需要索引器,為什么有人會使用vector [0]而不是vector.X?
如果index不必一定是integer ,則可以引入枚舉 ,因此編譯器將保證在代碼的任何地方都不會使用無效的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.