Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

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

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

------

Результат

Inside Main, before calling the method, the first element is: 1

Inside the method, the first element is: -3

Inside Main, after calling the method, the first element is: -3

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

Все изменения, выполняемые внутри метода, влияют на исходный массив в Main. В действительности исходный массив перераспределяется с помощью оператора new. Поэтому после вызова метода Change любая ссылка на arr указывает на массив из пяти элементов, созданный в методе Change.

Example: Swapping Two Strings

Swapping strings is a good example of passing reference-type parameters by reference. In the example, two strings, str1 and str2, are initialized in Main and passed to the SwapStrings method as parameters modified by the ref keyword. The two strings are swapped inside the method and inside Main as well.

class SwappingStrings

{

static void SwapStrings(ref string s1, ref string s2)

// The string parameter is passed by reference.

// Any changes on parameters will affect the original variables.

{

string temp = s1;

s1 = s2;

s2 = temp;

System.Console.WriteLine("Inside the method: {0} {1}", s1, s2);

}

static void Main()

{

string str1 = "John";

string str2 = "Smith";

System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);

SwapStrings(ref str1, ref str2); // Passing strings by reference

System.Console.WriteLine("Inside Main, after swapping: {0} {1}", str1, str2);

}

}

Output

Inside Main, before swapping: John Smith

Inside the method: Smith John

Inside Main, after swapping: Smith John

Code Discussion

In this example, the parameters need to be passed by reference to affect the variables in the calling program. If you remove the ref keyword from both the method header and the method call, no changes will take place in the calling program.

Пример. Перестановка двух строк

Перестановка строк представляет собой хороший пример передачи параметров ссылочного типа по ссылке. В данном примере две строки str1 и str2 инициализируются в Main и передаются в метод SwapStrings в качестве параметров, изменяемых по ключевому слову ref. Эти две строки переставляются внутри метода и также внутри Main.

----

Результат

Inside Main, before swapping: John Smith

Inside the method: Smith John

Inside Main, after swapping: Smith John

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

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

Constructors

Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.

If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values. Static classes and structs can also have constructors.

Using Constructors

Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class, and usually initialize the data members of the new object.

In the following example, a class named Taxi is defined by using a simple constructor. This class is then instantiated with the new operator. The Taxi constructor is invoked by the new operator immediately after memory is allocated for the new object.

public class Taxi

{

public bool isInitialized;

public Taxi()

{

isInitialized = true;

}

}

class TestTaxi

{

static void Main()

{

Taxi t = new Taxi();

System.Console.WriteLine(t.isInitialized);

}

}

A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.