我有一個自定義類Matrix,我已經應用了indexer它,因此它接受賦值和讀取值作為多維陣列。的Matrix類建構式接受rows和columns作為基質alrernative對天然陣列引數。
當我嘗試分配值時,出現以下例外:
Stack overflow. Repeat 24101 times: at Matrix.set_Item(Int32, Int32, Int32)
下面列出了我的 Matrix 類的最終代碼。
矩陣類
class Matrix
{
//declare the variable to hold the number of columns
private int cols;
//declare the variable to hold the number of rows
private int rows;
//define the constructor to accept the above arguments from a user and assign
public Matrix(int rows, int cols)
{
this.rows=rows;
this.cols=cols;
}
//apply indexing structure to this class to make it accept array operations(multidimensional)
public int this[int rows,int cols]
{
get
{
return matrixA[rows,cols];
}
set
{
matrixA[rows,cols] = value;
}
}
主要的
//declare the Matrix object
static Matrix matrixA;
//the lines below shows how to use the Matrix class
static void Main(string args[])
{
Console.WriteLine("Enter the number of rows");
int m = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter the number of columns");
int n = Int32.Parse(Console.ReadLine());
matrixA = new Matrix(m, n);
for (int i = 0; i < m; i )
{
for (int j = 0; j < n; j )
{
//i suppose the setter is invoked by this code
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
}
uj5u.com熱心網友回復:
您的 Matrix 類實際上沒有任何地方可以存盤任何資料;將矩陣的資料存盤放在Matrix 類中:
class Matrix
{
private int[,] _data;
//define the constructor to accept the above arguments from a user and assign
public Matrix(int rows, int cols)
{
_data = new int[rows,cols];
}
//apply indexing structure to this class to make it accept array operations(multidimensional)
public int this[int row, int col]
{
get
{
return _data[row,col];
}
set
{
_data[row,col] = value;
}
}
我想你已經把你的 Matrix 類放在你的 Program 類中(因此 Matrix 的 setter 如何能夠訪問靜態 matrixA 變數..) - 我現在要說的是,堅持“永遠不要把一個類放在另一個類中”的規則. class-inside-class 確實有效/是合法的 C# 語法,并且在某些情況下它可能是可取的,但通常(尤其是在開始時)并非如此;避免這樣做。如果您必須這樣做才能“讓其他事情正常作業”,那么這可能表明其他地方存在問題
主要是:
static void Main(string[] args) //in c# we put [] after the type, not the argument name
{
Console.WriteLine("Enter the number of rows");
int m = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter the number of columns");
int n = Int32.Parse(Console.ReadLine());
var matrixA = new Matrix(m, n);
...
至于為什么一切都出錯了:

您嘗試matrixA在回圈中訪問(紅色箭頭) - 這意味著您正在訪問matrixAmain 的頂部。您正在嘗試設定一個值,以便 C# 運行設定的代碼。做的第一件事set是訪問matrixA(綠線)以執行 a set,所以 C# 開始呼叫set(藍線),這意味著它只是在一個無限回圈中轉來轉去,藍/綠/藍/綠...
嘗試使用getter 的行為相同;您的代碼實際上從未獲取或存盤任何資料,因為沒有任何資料存盤,它只是一遍又一遍地訪問自身
當您將資料保留在類中時不會發生這種情況,因為 setter 最終不會訪問自身;它改為訪問資料存盤。
在一個更簡單的例子中:
class Person{
string name;
void SetNameBroken(string nameToSet){
SetNameBroken(nameToSet);
}
void SetNameWorking(string nameToSet){
name = nameToSet;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386027.html
上一篇:合并陣列中的專案,包括子專案
