2015-07-12 185 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/ –