![](/img/trans.png)
[英]Can C# (somehow) work out the type constraints itself when a generic type is passed as a generic type reference?
[英]C# - When reference type is passed using the out keyword, then can calling function code control the outer object?
在C#中,我知道在傳遞ref類型時,默認情況下會按值傳遞-值是地址,因此內部函數中對象屬性的任何更改也將反映在外部對象上。 但是,將內部對象分配為null或另一個對象或創建新對象(使用new關鍵字)不會影響外部對象。 為了達到更高的要求,我們需要使用ref關鍵字通過ref傳遞引用類型(對象)。
這個問題是關於out關鍵字的。 使用out關鍵字傳遞值類型時,地址將傳遞給調用函數,並且任何更新也將反映給外部對象。
但是,當使用out關鍵字傳遞引用類型(例如Car類的對象)時,調用函數代碼可以控制外部對象嗎?
function foo(out Car x)
{
x=null //or x=new Car(); //or x.speed=0
//Will the last one (x.speed=0) reflect to outer object, where as the
//1st 2 - that is - the null or new assignments wont reflect?)
}
Car c= new Car();
c.speed=100;
foo(out c);
console.writeline(x.speed);
現在,外部對象“ c”是否指向在函數中創建的新對象?
還是我們沒有使用out關鍵字通過ref傳遞的概念?
out
與ref
完全相同。 因此,它的工作方式相同,但在外觀上存在一些差異:
out
參數中傳遞未初始化的變量(在ref
參數中,您必須傳遞初始化變量) c.speed=0
類的c.speed=0
之前,必須首先為其分配一個值。 Ref用於將引用傳遞給變量,因此您可以對其進行更改。 Out僅用於返回值,它不關心傳遞的對象,如果您的執行分支未在方法內部設置值或在設置值之前使用該值,則它將導致編譯錯誤。
因此,在您的情況下,實例化c不會執行任何操作。 結果為null,並且嘗試訪問.speed時將獲得運行時異常(我認為是c而不是x)
代碼不帶:
Car c;
foo(out c); //if foo doesn't set c, you get compile errors
// now c is set by foo
參考代碼:
Car c=new Car();
foo(ref c);
// c was perhaps modified or set by foo
帶有ref的代碼無法編譯:
Car c;
foo(ref c); //error because c is not instantiated
無法編譯的代碼:
static void foo(out string text) {
DoSomethingWith(text); //error because text is not instantiated
text="something";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.