Out 和 Ref 引數
值型別(結構和列舉)通過值傳遞給函式:將為函式提供副本,而不是對變數的引用。所以以下功能不會做任何事情。
void add_three (int x) {
x += 3;
}
int a = 39;
add_three (a);
assert (a == 39); // a is still 39
要更改此行為,你可以使用 ref
關鍵字。
// Add it to the function declaration
void add_three (ref int x) {
x += 3;
}
int a = 39;
add_three (ref a); // And when you call it
assert (a == 42); // It works!
out
以相同的方式工作,但你必須在函式結束之前為此變數設定一個值。
string content;
FileUtils.get_contents ("file.txt", out content);
// OK even if content was not initialized, because
// we are sure that it got a value in the function above.
print (content);