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

Параметры методов

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

Параметры, принимаемые методом, также указываются в скобках, но при этом необходимо указать имя и тип каждого из параметров. Это имя не обязательно должно совпадать с именем передаваемого аргумента. Пример.

public static void PassesInteger()

{

int fortyFour = 44;

TakesInteger(fortyFour);

}

static void TakesInteger(int i)

{

i = 33;

}

В этом примере метод с именем PassesInteger передает аргумент методу с именем TakesInteger. Внутри метода PassesInteger этот аргумент имеет имя fortyFour, но в методе TakeInteger он является параметром с именем i. Этот параметр существует только в методе TakesInteger. Именем i можно обозначить произвольное количество других переменных, и они могут иметь любой тип, если только они не являются параметрами или переменными, объявляемыми внутри этого метода.

Обратите внимание, что метод TakesInteger присваивает переданному аргументу новое значение. Можно предположить, что это изменение отразится на переменной метода PassesInteger после выполнения метода TakeInteger, но на самом деле значение переменной fortyFour останется неизменным. Это связано с тем, что тип int является типом значения. По умолчанию при передаче методу типа значения передается копия объекта, а не сам объект. Поскольку метод работает с копией, изменения параметра не оказывают влияния на значения переменной в вызывающем методе. Типы значения называются так потому, что вместо самого объекта передается копия этого объекта. То есть передается значение, а не объект.

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

This differs from reference types, which are passed by reference. When an object that is based on a reference type is passed to a method, no copy of the object is made. Instead, a reference to the object that is being used as a method argument is made and passed. Changes made through this reference will therefore be reflected in the calling method. A reference type is created by using the class keyword as in the following example:

public class SampleRefType

{

public int value;

}

Now, if an object that is based on this type is passed to a method, the object will be passed by reference. For example:

public static void TestRefType()

{

SampleRefType rt = new SampleRefType();

rt.value = 44;

ModifyObject(rt);

System.Console.WriteLine(rt.value);

}

static void ModifyObject(SampleRefType obj)

{

obj.value = 33;

}

This example essentially does the same thing as the previous example. But, because a reference type is used, the modification made by ModifyObject is made to the object that is created in the TestRefType method. The TestRefType method will therefore display the value 33.

Эти типы отличаются от ссылочных типов, для которых значения передаются по ссылке. При передаче методу объекта, имеющего ссылочный тип, копия объекта не создается. Вместо этого создается и передается ссылка на объект, используемый в качестве аргумента метода. Изменения объекта, осуществляемые с помощью этой ссылки, будут доступны и в вызывающем методе. В следующем примере ключевое слово class указывает на то, что создается объект ссылочного типа.

public class SampleRefType

{

public int value;

}

Теперь при передаче методу объекта этого типа объект будет передаваться по ссылке. Пример.

public static void TestRefType()

{

SampleRefType rt = new SampleRefType();

rt.value = 44;

ModifyObject(rt);

System.Console.WriteLine(rt.value);

}

static void ModifyObject(SampleRefType obj)

{

obj.value = 33;

}

В этом примере выполняются те же действия, что и в предыдущем примере. Но поскольку используется ссылочный тип, изменения в методе ModifyObject относятся к объекту, созданному в методе created in the TestRefType. Поэтому в методе TestRefType на экран будет выведено значение 33.

Дополнительные сведения см. в разделе Передача параметров ссылочного типа.

Return Values

Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers:

class SimpleMath

{

public int AddTwoNumbers(int number1, int number2)

{

return number1 + number2;

}

public int SquareANumber(int number)

{

return number * number;

}

}

To use a value returned from a method, the calling method can use the method call itself anywhere a value of the same type would be sufficient. You can also assign the return value to a variable. For example, the following two code examples accomplish the same goal:

int result = obj.AddTwoNumbers(1, 2);

obj.SquareANumber(result);

obj.SquareANumber(obj.AddTwoNumbers(1, 2));

Using an intermediate variable, in this case, result, to store a value is optional. It may help the readability of the code, or it may be necessary if the value will be used more than one time.

Note:

A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.