Passing Value-Type Parameters



A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Therefore, passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the variable. If you want the called method to change the value of the parameter, you have to pass it by reference, using the ref or out keyword. For simplicity, the following examples use ref.

Example: Passing Value Types by Value

The following example demonstrates passing value-type parameters by value. The variable n is passed by value to the method SquareIt. Any changes that take place inside the method have no affect on the original value of the variable.

class PassingValByVal { static void SquareIt(int x) // The parameter x is passed by value. // Changes to x will not 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(n); // Passing the variable by value.    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: 5

Code Discussion

The variable n, being a value type, contains its data, the value 5. When SquareIt is invoked, the contents of n are copied into the parameter x, which is squared inside the method. In Main, however, the value of n is the same, before and after calling the SquareIt method. In fact, the change that takes place inside the method only affects the local variable x.


Передача параметров типа значения

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

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

В следующем примере демонстрируется передача параметров типа значения с помощью значения. Переменная 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.


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

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






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