Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
20
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 15 DELEGATES

Invoking Delegates with Return Values

If a delegate has a return value and more than one method in its invocation list, the following occurs:

The value returned by the last method in the invocation list is the value returned from the delegate invocation.

The return values from all the other methods in the invocation list are ignored.

For example, the following code declares a delegate that returns an int value. Main creates an object of the delegate and adds two additional methods. It then calls the delegate in the WriteLine statement and prints its return value. Figure 15-10 shows a graphical representation of the code.

delegate int MyDel( );

 

// Declare method with return value.

class MyClass

{

 

 

int IntValue = 5;

 

 

public int

Add2() {

IntValue += 2; return IntValue;}

public int

Add3() {

IntValue += 3; return IntValue;}

}

 

 

 

class Program

{

 

 

static void Main( )

{

 

MyClass

mc = new

MyClass();

 

MyDel mDel = mc.Add2;

// Create and initialize the delegate.

mDel +=

mc.Add3;

 

// Add a method.

mDel +=

mc.Add2;

 

// Add a method.

 

Console.WriteLine("Value: {0}", mDel() );

}

 

 

}

Invoke the delegate and use the return value.

This code produces the following output:

Value: 12

Figure 15-10. The return value of the last method executed is the value returned by the delegate.

381

CHAPTER 15 DELEGATES

Invoking Delegates with Reference Parameters

If a delegate has a reference parameter, the value of the parameter can change upon return from one or more of the methods in the invocation list.

When calling the next method in the invocation list, the new value of the parameter—not the initial value—is the one passed to the next method.

For example, the following code invokes a delegate with a reference parameter. Figure 15-11 illustrates the code.

delegate void MyDel( ref int X );

class MyClass

{

public void Add2(ref int x) { x += 2; } public void Add3(ref int x) { x += 3; } static void Main()

{

MyClass mc = new MyClass();

MyDel mDel = mc.Add2; mDel += mc.Add3;

mDel += mc.Add2;

int x = 5; mDel(ref x);

Console.WriteLine("Value: {0}", x);

}

}

This code produces the following output:

Value: 12

Figure 15-11. The value of a reference parameter can change between calls.

382

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]