Delegates


Delegates - type-safe pointers to methods - are discussed in Chapter 7, “Delegates and Events.” In all three languages the keyword delegate can be used to define a delegate. The difference is with using the delegate.

The sample code shows a class Demo with a static method Foo() and an instance method Bar(). Both of these methods are invoked by delegate instances of type DemoDelegate. DemoDelegate is declared to invoke a method with void return type and an int parameter.

Using the delegate, C# 2.0 supports delegate inference, where the compiler creates a delegate instance and passes the address of the method.

With C# and C++/CLI, two delegates can be combined into one by using the + operator.

  // C# public delegate void DemoDelegate(int x); public class Demo {    public static void Foo(int x) { }    public void Bar(int x) { } } Demo d = new Demo(); DemoDelegate d1 = Demo.Foo; DemoDelegate d2 = d.Bar; DemoDelegate d3 = d1 + d2; d3(11); 

Delegate inference is not possible with C++/CLI. With C++/CLI, it is required that you create a new instance of the delegate type and pass the address of the method to the constructor.

  // C++/CLI public delegate void DemoDelegate(int x); public ref class Demo { public:    static void Foo(int x) { }    void Bar(int x) { } }; Demo^ d = gcnew Demo(); DemoDelegate^ d1 = gcnew DemoDelegate(&Demo::Foo); DemoDelegate^ d2 = gcnew DemoDelegate(d, &Demo::Bar); DemoDelegate^ d3 = d1 + d2; d3(11); 

Similarly to C++/CLI, Visual Basic does not support delegate inference. You have to create a new instance of the delegate type and pass the address of a method. Visual Basic has the AddressOf operator to pass the address of a method.

Visual Basic doesn’t overload the + operator for delegates, so it is necessary to invoke the Combine() method from the Delegate class. The Delegate class is written inside brackets because Delegate is a Visual Basic keyword, and thus it is not possible to use a class with the same name. Putting brackets around Delegate makes sure that the class is used instead of the Delegate keyword.

  ' Visual Basic Public Delegate Sub DemoDelegate(ByVal x As Integer) Public Class Demo    Public Shared Sub Foo(ByVal x As Integer)       '    End Sub    Public Sub Bar(ByVal x As Integer)       '    End Sub End Class Dim d As New Demo() Dim d1 As New DemoDelegate(AddressOf Demo.Foo) Dim d2 As New DemoDelegate(AddressOf d.Bar) Dim d3 As DemoDelegate = [Delegate].Combine(d1, d2) d3(11) 




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net