2015-07-12 183 views
3

我需要一種方法來跟蹤網格中的行數和列數。如果我使用System.Point,我總是會忘記「x」是行數還是列數。所以我有下面的課。使用不同名稱的系統類?

但我想知道是否有一種方法來使用System.Point,與不同的命名皮膚?換句話說,我做而不是想要在System.Point上定義一個通用的「NRows」或「NColumns」方法。但我確實希望能夠返回代碼將會看作「NRowsColumns」對象的對象,但實際上它編譯爲System.Point。當訪問「NRowsColumns」對象時,我們使用字段「NRows」和「NColumns」而不是「x」和「y」。但是在底層,它實際上編譯爲System.Point。

理想情況下,這個定義不會侷限於單個文件。

public class NRowsColumns 
{ 
    public int NRows {get;set;} 
    public int NColumns {get;set;} 
    public NRowsColumns(int nRows, int nColumns) 
    { 
    this.NRows = nRows; 
    this.NColumns = nColumns; 
    } 
} 

回答

1

您可以使用conversion operators讓你的代碼中使用您的NRowsColumnsPoint互換。

請注意,這不是一個完美的解決方案。來回創建對象會影響您應該進行調查。

implicit operator轉換添加到您的現有類:

public class NRowsColumns 
{ 
    public int NRows { get; set; } 
    public int NColumns { get; set; } 
    public NRowsColumns(int nRows, int nColumns) 
    { 
     this.NRows = nRows; 
     this.NColumns = nColumns; 
    } 

    public static implicit operator NRowsColumns(Point p) 
    { 
     return new NRowsColumns(p.X, p.Y); 
    } 

    public static implicit operator Point(NRowsColumns rowsColumns) 
    { 
     return new Point(rowsColumns.NRows, rowsColumns.NColumns); 
    } 
} 

現在你可以來回轉換:

Point point1 = new Point(5, 10); 
NRowsColumns nRowsColumns = point1; 
Point point2 = nRowsColumns; 

請記住,每一個「轉換」是一個新的對象。

3

不,你不能「重命名」那樣的成員。你可以參考System.Point作爲NRowsColumns如果你真的想,作爲

using NRowsColumns = System.Point; 

...但它仍然具有相同的成員System.Point

這將是簡單的只是落實NRowsColumns組成一個System.Point但:

public class NRowsColumns 
{ 
    private Point point; 

    public int NRows 
    { 
     get { ... } // Code using point 
     set { ... } // Code using point 
    } 

    ... 
} 

說了:

  • 我看不到一個真正Point有什麼有許多行和列。爲什麼不只是有兩個整數?
  • 我會在這裏重溫你的命名...... N前綴是非常規的。我可能會把它稱爲GridSizeRowsColumns - 雖然這似乎不必要作爲一個單獨的類型,一般來說。 (爲什麼你的網格本身不是通過RowsColumns屬性公開其大小?)
+0

關於命名的好建議。如果OP需要'NumberOfRows',那麼將其用作屬性名稱;否則就使用'行'。 「NRows」令人困惑。 –

0

爲什麼不直接從繼承點?

public struct NRowsColumns: Point 
{ 
    public int NRows {get {return base.x;}} 
    public int NColumns {get {return base.y;}} 
    public NRowsColumns(int nRows, int nColumns) 
     : base(nRows, nColumns) 
    { 
    } 
} 
+0

在最好的時候,繼承是一個糟糕的主意。以這種表面方式鼓勵它的使用只是非常糟糕的建議。 –

+0

你爲什麼認爲這是一個壞主意?整個OOP概念是建立在繼承(等等)之上的。我同意它應該用來擴展現有的對象功能,但我沒有看到使用它來改善代碼可讀性的任何錯誤。請賜教。 –

+0

你可以在http://simpleprogrammer.com/2010/01/15/inheritance-is-inherently-evil/ –