我從未意識到過這樣的問題。如果我傳遞了一個具有特定類型但尚未實例化的變量,那麼它不應該被視爲一個指針嗎?在這個例子中,爲什麼如果方法GetEmployee創建一個新的實例,我回到了單擊事件的範圍時,我得到了空值。傳遞一個類的變量作爲之前定義爲null的參數
我知道爲了使它工作,我可以將參數定義爲ref或out,但Employee是一個最初被定義爲null的類,但是當我做新的時候,我會在內存中分配一個空間,不要鏈接到變量?爲什麼我以後失去價值?
如果我傳遞一個對象,那麼當我回到click事件的範圍時,內部方法中所有修改過的屬性將保持不變的情況將完全不同。
這將無法正常工作
protected void btnTest_Click(object sender, System.EventArgs e)
{
Employee employee = null;
bool created = GetEmployee(employee);
}
這將工作
protected void btnTest_Click(object sender, System.EventArgs e)
{
Employee employee = new Employee();
bool created = GetEmployee(employee);
}
其餘
private bool GetEmployee(Employee employee)
{
if (employee == null)
{
employee = new Employee();
}
employee.ID = 1;
employee.Name = "John";
return true;
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
}
UPDATE:
的COM把事情稍微折騰一下。這也將失敗,因爲該對象從未被設置爲不同的東西,以空
protected void btnTest_Click(object sender, System.EventArgs e)
{
int id = 1;
Employee employee = this.LoadFromDatabase(id);
bool created = GetEmployee(employee);
}
private Employee LoadFromDatabase(id)
{
//In the inner service method if it is not found it will return null
return Service.Instance.LoadFromDatabase(id);
}
private bool GetEmployee(Employee employee)
{
if (employee == null)
{
employee = new Employee();
}
employee.ID = 1;
employee.Name = "John";
return true;
}
https://blogs.msdn.microsoft.com/csharpfaq/2004/03/11/how-are-parameters-passed-in-c-are-they-by-reference-by-value/ – Jakotheshadows
對,在這種情況下,值是引用,你不能改變引用,因此分配某些參數在調用者中沒有任何作用。 – Jakotheshadows
我不確定它是如何錯誤地傳遞參考的。 REFERENCE是按值傳遞的。我會編輯我的答案,以明確表示。 – Jakotheshadows