我試圖從其他類中更改對象值。理想情況下,我想將對象作爲參數傳遞給構造函數/方法。到目前爲止,我讀過的東西,當作爲參數傳遞時,對象的行爲與引用相同,參數值在本地複製以用於方法的主體。所以這裏是我測試的幾個配置:C#通過另一個類更改對象值
案例#1。失敗
class Processor
{
DataTable table;
public Processor(DataTable table)
{
this.table = table;
}
public void InitializeTable()
{
if (table != null)
{
// Fill data into DataTable.
}
}
}
static void Main(string[] args)
{
DataTable mainTable = new DataTable();
Processor processor = new Processor(mainTable);
processor.InitializeTable();
// mainTable still empty
}
我想Processor
表持有同樣的參考mainTable
,但Main
執行mainTable
年底還空着,而Processor
表中瀰漫。
案例#2。失敗
public Processor(ref DataTable table)
{
this.table = table;
}
我使用ref
簽名試過,但結果還是一樣(mainTable
是空的)。
案例#3。失敗
public void InitializeTable(DataTable table)
{
// Fill data into table
}
我已經去除了構造函數和飼料mainTable
到InitializeTable()
方法和結果還是一樣(mainTable
是空的)。
案例#4。作品!
public void InitializeTable(ref DataTable table)
{
// Fill data into table
}
最後這個工程!將ref mainTable
送入InitializeTable
現在成功填寫mainTable
。這背後有什麼解釋?爲什麼構造函數沒有與mainTable
相同的引用?當傳遞對象作爲參數時,爲什麼ref
關鍵字仍然需要傳遞它的引用?
'InitializeTable()'實際上做了什麼?在第一個完整的例子中,我肯定希望'mainTable'反映所做的任何修改,因爲在內存中只有一個實際的'DataTable'實例化了。 – David
簡單的查詢從數據庫中獲取數據,並將其分配給表。是的,我也有相同的假設,但只有case#4填充mainTable。 – Suwandy
「你把它分配給表」是什麼意思?如果代碼沒有達到你期望的程度,不要模糊地描述代碼,並假定它必須工作,實際上檢查它。 – David