C# 是否使用具有不同名称的系统类?
我需要一种方法来跟踪网格中的行数和列数。如果我使用System.Point,我总是会忘记“x”是行数还是列数。所以我有下面的课程 但我想知道是否有一种方法可以使用System.Point,使用不同的命名皮肤?换句话说,我不想在System.Point上定义一般的“NRows”或“NColumns”方法。但我确实希望能够返回一个对象,代码将其视为“NRowsColumns”对象,但实际上编译为System.Point。访问“NRowsColumns”对象时,我们使用字段“NRows”和“NColumns”而不是“x”和“y”。但在引擎盖下,它实际上编译成一个系统点 理想情况下,此定义不会局限于单个文件C# 是否使用具有不同名称的系统类?,c#,naming,renaming,C#,Naming,Renaming,我需要一种方法来跟踪网格中的行数和列数。如果我使用System.Point,我总是会忘记“x”是行数还是列数。所以我有下面的课程 但我想知道是否有一种方法可以使用System.Point,使用不同的命名皮肤?换句话说,我不想在System.Point上定义一般的“NRows”或“NColumns”方法。但我确实希望能够返回一个对象,代码将其视为“NRowsColumns”对象,但实际上编译为System.Point。访问“NRowsColumns”对象时,我们使用字段“NRows”和“NColu
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;
}
}
您可以使用以允许代码交替使用NRowsColumns
和点
注意,这不是一个完美的解决方案。来回创建对象会产生影响,您应该对此进行调查
将隐式运算符
转换添加到现有类:
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;
请记住,每次“转换”都是一个新对象。不,您不能像这样“重命名”成员。如果确实需要,可以将System.Point
称为NRowsColumns
,如
using NRowsColumns = System.Point;
。。。但它仍然拥有与System.Point
相同的成员
通过组合一个系统来实现NRowsColumns
会更简单。尽管:
public class NRowsColumns
{
private Point point;
public int NRows
{
get { ... } // Code using point
set { ... } // Code using point
}
...
}
尽管如此:
- 我看不出
点
真的与许多行和列有关。为什么不只用两个整数呢
- 我会在这里重温你的名字。。。
N
前缀是非常规的。我可能会用行
和列
将其称为GridSize
——尽管一般来说,这似乎不需要作为单独的类型。(为什么网格本身不通过行
和列
属性公开其大小?)
为什么不直接从点继承
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)
{
}
}
在最好的时候,继承是个坏主意。以这种肤浅的方式鼓励它的使用显然是个坏建议。你为什么认为这是个坏主意?整个OOP概念是建立在继承(以及其他)的基础上的。我同意应该使用它来扩展现有的对象功能,但我认为使用它来提高代码可读性没有任何错误。请告诉我。你可以在@DavidArno找到一个很好的解释来解释继承的邪恶,以及为什么接口和组合可以产生更好的代码,但你不能说“好吧,我给你100%的解释,继承是邪恶的,永远不要使用它”。但在这种情况下,我同意你的看法。这不是使用继承的最佳地点,严格地说,使用继承不超过必要的范围是一种良好的做法。@Fabjan,我可以这么说,尽管我承认这是一种可以采用的速度设置位置。我完全避免使用goto
、switch
和继承,我的代码更适合它。其他人将及时赶上这个职位。:)关于命名的好建议。如果OP想要NumberOfRows
,则将其用作属性名称;否则只需使用行
<代码>NRows
令人困惑。