X hits on this document





309 / 396


class Test { static void Main() { D cd1 = new D(C.M1);// M1 D cd2 = new D(C.M2);// M2 D cd3 = cd1 + cd2;// M1 + M2 D cd4 = cd3 + cd1; // M1 + M2 + M1 D cd5 = cd4 + cd3; // M1 + M2 + M1 + M1 + M2 }


When cd1 and cd2 are instantiated, they each encapsulate one method. When cd3 is instantiated, it has an invocation list of two methods, M1 and M2, in that order. cd4’s invocation list contains M1, M2, and M1, in that order. Finally, cd5’s invocation list contains M1, M2, M1, M1, and M2, in that order. For more examples of combining (as well as removing) delegates, see §‎15.3.

15.2 Delegate instantiation

An instance of a delegate is created by a delegate-creation-expression (§‎ The newly created delegate instance then refers to either:

The static method referenced in the delegate-creation-expression, or

The target object (which cannot be null) and instance method referenced in the delegate-creation-expression, or

Another delegate.

For example:

delegate void D(int x);

class C { public static void M1(int i) {...} public void M2(int i) {...} }

class Test { static void Main() { D cd1 = new D(C.M1);// static method Test t = new C(); D cd2 = new D(t.M2);// instance method D cd3 = new D(cd2);// another delegate } }

Once instantiated, delegate instances always refer to the same target object and method. Remember, when two delegates are combined, or one is removed from another, a new delegate results with its own invocation list; the invocation lists of the delegates combined or removed remain unchanged.

15.3 Delegate invocation

C# provides special syntax for invoking a delegate. When a non-null delegate instance whose invocation list contains one entry is invoked, it invokes the one method with the same arguments it was given, and returns the same value as the referred to method. (See §‎ for detailed information on delegate invocation.) If an exception occurs during the invocation of such a delegate, and that exception is not caught within the method that was invoked, the search for an exception catch clause continues in the method that called the delegate, as if

296Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views1364
Page views1364
Page last viewedSun Jan 22 07:56:56 UTC 2017