logo
CSharp_Prog_Guide

Пример. Передача типов значений с помощью ссылки.

Следующий пример похож на предыдущий за исключением того, что в нем параметр передается с помощью ключевого слова ref. После вызова метода значение параметра изменяется.

-----

Результат

The value before calling the method: 5

The value inside the method: 25

The value after calling the method: 25

Рассмотрение кода

В этом примере передается не значение переменной n а ссылка на переменную n. Параметр x не является типом int; он является ссылкой на тип int, в данном случае ссылкой на переменную n. Поэтому при возведении в квадрат параметра x внутри метода фактически в квадрат возводится переменная, на которую ссылается параметр x — переменная n.

Example: Swapping Value Types

A common example of changing the values of the passed parameters is the Swap method, where you pass two variables, x and y, and have the method swap their contents. You must pass the parameters to the Swap method by reference; otherwise, you will be dealing with a local copy of the parameters inside the method. The following is an example of the Swap method that uses reference parameters:

static void SwapByRef(ref int x, ref int y)

{

int temp = x;

x = y;

y = temp;

}

When you call this method, use the ref keyword in the call, like this:

static void Main()

{

int i = 2, j = 3;

System.Console.WriteLine("i = {0} j = {1}" , i, j);

SwapByRef (ref i, ref j);

System.Console.WriteLine("i = {0} j = {1}" , i, j);

}

Output

i = 2 j = 3

i = 3 j = 2