158
❘
CHAPTER 8
Creating WindoWs Forms appliCations
Whenever the user clicks Fire Event, the code calls
btnFireEvent_Click()
because this is the
event handler assigned to the
btnFireEvent.Click
event. The code inside
btnFireEvent_Click()
simply calls
ThisEvent.Fire()
with a message of Hello World. At this point, the event calls
HandleMsg()
to display the message using a standard message box.
WHY NoT uSE DElEgATES?
When you write an application using a language such as C# or Visual Basic.NET,
you usually rely on delegates to create custom events. Using a delegate is simple and
well understood. You can see examples all over the place, but check out the example
at
http://www.akadia.com/services/dotnet_delegates_and_events.html
for
a good overview.
Theoretically, there must be a way to use delegates with IronPython too, but the
process would be extremely difficult and error prone for a number of reasons. The
fact is that IronPython simply doesn’t provide good support for delegates, so using
the other techniques described in this chapter simply works better.
However, it’s interesting to view one particular issue when considering delegates in
IronPython. You must provide a method that’s compatible with delegates in order to
use delegates. As part of the preparation for this chapter, I played around with del-
egates for a while and found that you simply can’t obtain the method information in
a way that delegates will understand. To see this for yourself, try this code:
import System
class MyClass:
def MyMsgDisplay(self, Msg, Title):
print Msg, Title
for Methods in System.Type.GetMethods(type(MyClass)):
print Methods
When you run this code, you’ll begin to understand something interesting about
IronPython. The output from this example does include methods such as
__new__
()
,
ToString()
, and
__repr__()
, but nowhere will you see
MyMsgDisplay()
. It
turns out that
MyMsgDisplay()
is implemented as part of the IronPython run time,
so it looks like this (even though the code appears on two lines in the book, you
must type it as a single line in your code):
System.Object Call(IronPython.Runtime.CodeContext, System.Object[])
All that code is the little
MyMsgDisplay()
method. What you’re seeing is the method
that marshals information to the IronPython run time. For example,
IronPython
.Runtime.CodeContext
is actually
self
. The
System.Object[]
array is a collection
of two objects,
Msg
and
Title
, sent to
MyMsgDisplay()
. Unless something changes
drastically, you won’t ever be able to use delegates in IronPython.
548592c08.indd 158
2/24/10 12:48:13 PM
www.finebook.ir
Do'stlaringiz bilan baham: |