我正在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