logo search
CSharp_Prog_Guide

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

В следующем примере демонстрируется передача параметров типа значения с помощью значения. Переменная n передается с помощью значения в метод SquareIt. Любые изменения, выполняемые внутри метода, не влияют на значение переменной.

----

Результат

The value before calling the method: 5

The value inside the method: 25

The value after calling the method: 5

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

Переменная n, имеющая тип значения, содержит данные, значение 5. При вызове метода SquareIt содержимое переменной n копируется в параметр x, который возводится в квадрат внутри метода. Однако в методе Main значение переменной n остается одинаковым до и после вызова метода SquareIt. Фактически, изменение, выполняемое внутри метода, влияет только на локальную переменную x.

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.