Example: Passing Value Types by Reference 
";


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Example: Passing Value Types by Reference



The following example is the same as the previous example, except for passing the parameter using the ref keyword. The value of the parameter is changed after calling the method.

class PassingValByRef { static void SquareIt(ref int x) // The parameter x is passed by reference. // Changes to x will affect the original value of x. { x *= x; System.Console.WriteLine("The value inside the method: {0}", x); } static void Main() { int n = 5; System.Console.WriteLine("The value before calling the method: {0}", n); SquareIt(ref n); // Passing the variable by reference. System.Console.WriteLine("The value after calling the method: {0}", n); } }

Output

The value before calling the method: 5

The value inside the method: 25

The value after calling the method: 25

Code Discussion

In this example, it is not the value of n that is passed; rather, a reference to n is passed. The parameter x is not an int; it is a reference to an int, in this case, a reference to n. Therefore, when x is squared inside the method, what actually gets squared is what x refers to: n.


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

Следующий пример похож на предыдущий за исключением того, что в нем параметр передается с помощью ключевого слова 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

 


Пример. Замена типов значений.

Распространенным примером замены значений передаваемых параметров является метод Swap, в который передаются две переменные, x и y, и метод меняет местами их содержимое. Параметры необходимо передавать в метод Swap с помощью ссылки. В противном случае внутри метода будут использоваться локальные копии параметров. Ниже приведен пример использования ссылочных параметров в методе Swap.

static void SwapByRef(ref int x, ref int y) { int temp = x; x = y; y = temp; }

При вызове этого метода следует использовать ключевое слово ref следующим образом.

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); }

Результат

i = 2 j = 3

i = 3 j = 2

 


Passing Reference-Type Parameters

A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref or out keyword. For simplicity, the following examples use ref.



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 87; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.137.192.3 (0.005 с.)