Information Technology Reference
In-Depth Information
This code produces the following output:
Print1 -- instance
Print2 -- static
Print1 -- instance
Print2 -- static
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 will be 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-9 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
Search WWH ::




Custom Search