下面說明相同點:
out 關鍵字修飾的方法參數為輸出參數,與引用型別類似,輸出參數也不會建立新的記憶體區域。不同點:
out 變數前可不進行初始化,但在方法返回前必須給 out 參數賦值;ref 則要求變數在傳遞前必須初始化。out 關鍵字的用途:
一般方法只能回傳一個值,當希望方法回傳多個值時,宣告 out 方法很有用。
範例:
static void Method(out int i, out string s1, out string s2)
{
i = 44;
s1 = "I've been returned";
s2 = null;
}
也就是在方法返回後,給事先宣告的變數在方法中賦值。
再看一個 out 的範例:
class TestOut
{
static void SplitPath(string path, out string dir, out string name)
{
int i = path.Length;
// 以下計算路徑的節點
while (i > 0)
{
char ch = path[i - 1];
if (ch == '\\' || ch == '/' || ch == ':')
break;
else
i--;
}
dir = path.Substring(0, i); // 從 path 字串第 0 個字元取前 i 個字元指派給 dir
name = path.Substring(i); // 取出後 i 個字元指派給 name
}
static void Main(string[] args)
{
string dir, name;
SplitPath("c:\\learncs\\hello.txt", out dir, out name);
Console.WriteLine(dir);
Console.WriteLine(name);
}
}