导航

ref和out

Posted on 2010-06-07 14:02  杨彬Allen  阅读(160)  评论(0)    收藏  举报

若想以传址方式遞送引數,C#提供了參數修飾字 ref。使用ref可是兩個變量都指向同一個內存位置。

應用這個功能來傳送大型的 「結構」(struct)非常有效。Example:

ref
class TestRef
{
static void FillArray(ref int[] arr)
{
// Create the array on demand:
if (arr == null)
{
arr
= new int[10];
}
// Fill the array:
arr[0] = 1111;
arr[
4] = 5555;
}

static void Main()
{
// Initialize the array:
// ref 要求在傳遞給「方法」之前,必須為它設定一個初始值,這與out不同.
int[] theArray = { 1, 2, 3, 4, 5 };

// Pass the array using ref:
FillArray(ref theArray);

// Display the updated array:
System.Console.WriteLine("Array elements are:");
for (int i = 0; i < theArray.Length; i++)
{
System.Console.Write(theArray[i]
+ " ");
}
}
}

 

為了彌補ref必須在傳遞給「方法」之前設初始值的不足,C#提供了out修飾字。

Out
class TestOut
{
static void FillArray(out int[] arr)
{
// Initialize the array:
arr = new int[5] { 1, 2, 3, 4, 5 };
}

static void Main()
{
int[] theArray; // Initialization is not required

// Pass the array to the callee using out:
FillArray(out theArray);

// Display the array elements:
System.Console.WriteLine("Array elements are:");
for (int i = 0; i < theArray.Length; i++)
{
System.Console.Write(theArray[i]
+ " ");
}
}
}