我正在C#中编写一个用于处理矩阵的类库,目前正在处理名为ComplexMatrix的Matrix的子类。 Matrix基类使用Int32数据类型(更高级的版本使用Double)和System.Numerics.Complex结构(.NET 4)的ComplexMatrix。当从基类继承ToString()时数据类型混淆
对于基类,我推翻的ToString()为:
| 1 2 |
| 3 4 | printed as {{1,2}{3,4}}
的System.Numerics.Complex结构覆盖在形式的ToString():
a+bi printed as (a,b) where a is real and b is imaginary
当ComplexMatrix重写的ToString ,我只是用了这个方法:
public override string ToString()
{
return base.ToString();
}
不幸的是,对于一个复杂的矩阵,下面的发生:
| 1+1i 1+2i |
| 2+1i 2+2i | printed as {{0,0}{0,0}} rather than {{(1,1),(1,2)}{(2,1)(2,2)}}
原来的ToString()我写的Matrix类代码:
public override string ToString()
{
StringBuilder matrixString = new StringBuilder();
string comma = "";
matrixString.Append("{");
for (int i = 0; i < this.Rows; i++)
{
matrixString.Append("{");
for (int j = 0; j < this.Columns; j++)
{
if (j == 0) comma = "";
else comma = ",";
matrixString.Append(comma + this.Elements[i, j].ToString());
}
matrixString.Append("}");
}
matrixString.Append("}");
return matrixString.ToString();
}
在上面的代码:
- this.Elements属性:在Matrix类,这是一个Int32类型的二维数组(更新,更高级版本中的Double);它是System.Numerics.Complex类型的ComplexMatrix
- this.Rows,this.Columns属性:行和列的分别是矩阵的数量
几个问题我已经是:
- 当在ComplexMatrix实例上调用ToString并调用基本ToString()方法时,是从Complex到Int32发生的尝试类型转换?
- 由于ComplexMatrix Elements属性(Complex [,]类型)隐藏了基类Elements属性(Int32 [,]类型),因此new关键字是必需的吗?
- “this”kwyword被视为Matrix类型而不是ComplexMatrix?
只是一个音符。 '公共重写字符串的ToString(){ 回报 base.ToString();你也可以删除它。 – 2011-05-27 14:35:20
另一个说明与该问题无关。我认为你的课堂体系颠倒了。基类应该总是更普遍的情况,而不是周围的方式。因此DoubleMatrix应该继承形式ComplexMatrix,因为double是复数形式的子类。这样,您只需要一个Complex [,]数组作为在基本情况下定义的矩阵元素的存储,它可以存储复数和双精度(您只需要在双精度和复数之间定义一个隐式转换)。一个int矩阵将继承DoubleMatrix,但我无法看到使用int Matrix。 – InBetween 2011-05-27 14:41:14