Chapter 10: Defi ning Class Members
265
Here, the partial method DoSomethingElse is defined and called in the first partial class definition,
and implemented in the second. The output, when
DoSomething is called from a console application, is
what you might expect:
DoSomething() execution started.
DoSomethingElse() called.
DoSomething() execution finished.
If you were to remove the second partial class definition or partial method implementation entirely (or
comment out the code), the output would be as follows:
DoSomething() execution started.
DoSomething() execution finished.
You might assume that what is happening here is that when the call to DoSomethingElse is made, the
runtime discovers that the method has no implementation and therefore continues executing the next
line of code. What actually happens is a little subtler. When you compile code that contains a partial
method definition without an implementation, the compiler actually removes the method entirely. It also
removes any calls to the method. When you execute the code, no check is made for an implementation
because there is no call to check. This results in a slight — but nevertheless significant — improvement in
performance.
As with partial classes, partial methods are useful when it comes to customizing autogenerated or
designer - created code. The designer may declare partial methods that you can choose to implement or
not depending on the situation. If you don ’ t implement them, you incur no performance hit because
effectively the method does not exist in the compiled code.
Consider at this point why partial methods can ’ t have a return type. If you can answer that to your own
satisfaction, you can be sure that you fully understand this topic — so that is left as an exercise for you.
Example Application
To illustrate some of the techniques you ’ ve been using so far, in this section you ’ ll develop a class
module that you can build on and make use of in subsequent chapters. The class module will contain
two classes:
Card — Representing a standard playing card, with a suit of club, diamond, heart, or spade, and
a rank that lies between ace and king .
Deck — Representing a full deck of 52 cards, with access to cards by position in the deck and the
ability to shuffle the deck .
You ’ ll also develop a simple client to ensure that things are working, but you won ’ t use the deck in a full
card game application — yet.
❑
❑
c10.indd 265c10.indd 265 3/24/08 3:36:52 PM3/24/08 3:36:52 PM
评论1
最新资源