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



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

Example: Passing Reference Types by Value

The following example demonstrates passing a reference-type parameter, arr, by value, to a method, Change. Because the parameter is a reference to arr, it is possible to change the values of the array elements. However, the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable, arr.

class PassingRefByVal { static void Change(int[] pArray) {    pArray[0] = 888; // This change affects the original element.    pArray = new int[5] {-3, -1, -2, -3, -4}; // This change is local.    System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]); }   static void Main() {    int[] arr = {1, 4, 5};    System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);      Change(arr);    System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]); } }

 


Передача параметров ссылочного типа

Переменная ссылочного типа не содержит непосредственные данные; она содержит ссылку на эти данные. Если параметр ссылочного типа передается по значению, можно изменить данные, на которые указывает ссылка, например, значение члена класса. Однако нельзя изменить значение самой ссылки; то есть нельзя использовать одну ссылку для выделения памяти для нового класса и его создания вне заданного блока. Для этого передайте параметр с помощью ключевого слова ref или out. Для простоты в следующем примере использовано ключевое слово ref.


Дата добавления: 2019-03-09; просмотров: 240; Мы поможем в написании вашей работы!

Поделиться с друзьями:






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