15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

OC182 ❘ ChaPTer 53 c#, visuAl bAsic, c++/cli, And f#<br />

// C++/CLI<br />

public ref class Resource<br />

{<br />

public:<br />

~Resource() // implement IDisposable<br />

{<br />

this->!Resource();<br />

}<br />

!Resource() // override Finalize<br />

{<br />

// release resource<br />

}<br />

};<br />

' Visual Basic<br />

Public Class Resource<br />

Implements IDisposable<br />

Public Sub Dispose() Implements IDisposable.Dispose<br />

Dispose(True)<br />

GC.SuppressFinalize(Me)<br />

End Sub<br />

Protected Overridable Sub Dispose(ByVal disposing)<br />

If disposing Then<br />

' Release embedded resources<br />

End If<br />

' Release resources of this class<br />

End Sub<br />

Protected Overrides Sub Finalize()<br />

Try<br />

Dispose(False)<br />

Finally<br />

MyBase.Finalize()<br />

End Try<br />

End Sub<br />

End Class<br />

code snippet CPPCLI/Resource.h<br />

code snippet VisualBasic/Resource.vb<br />

delegaTes<br />

Delegates — type-safe pointers to methods — are discussed in Chapter 8, “Delegates, Lambdas, <strong>and</strong><br />

Events.” In all four languages, the keyword delegate can be used to define a delegate. The difference is<br />

with using the delegate.<br />

The sample code shows a class Demo with a static method Foo() <strong>and</strong> an instance method Bar(). Both<br />

of these methods are invoked by delegate instances of type DemoDelegate. DemoDelegate is declared to<br />

invoke a method with void return type <strong>and</strong> an int parameter.<br />

When using the delegate, <strong>C#</strong> supports delegate inference, where the compiler creates a delegate instance <strong>and</strong><br />

passes the address of the method.<br />

With <strong>C#</strong> <strong>and</strong> C++/CLI, two delegates can be combined into one by using the + operator:<br />

// <strong>C#</strong><br />

public delegate void DemoDelegate(int x);<br />

public class Demo<br />

{<br />

public static void Foo(int x) { }<br />

public void Bar(int x) { }<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!