Creating the Simple Visual Basic.NET Extension
❘
363
Public Function Dec() As Calcs
Return New Calcs(Me.Data - 1)
End Function
End Class
The code begins with a constructor that accepts an
Int32
value as input. The example doesn’t
include a default constructor because IronPython needs to assign a value to the object during the
instantiation process. A default constructor would still need to assign a value to the private
Data
member, so it’s just better to assign a valid value to
Data
at the outset.
The
ToString()
override comes next. The default behavior for
ToString()
is to display the name of
the class. You must override this behavior to display the value of
Data
. Notice that you must access
Data
as
Me.Data
— the copy of
Data
associated with this particular instance of the
Calcs
class.
The four
Operator
methods are defined as
Shared
, rather than
Overrides
. The
Operator
methods
act as static class members so that you can use them naturally in IronPython. The input arguments
for each method are the objects you create within IronPython. Consequently, there isn’t any concept
of numeric type for
Value1
or
Value2
(you could theoretically use the same methods for any numeric
value). The actual math operation occurs on the
Data
member of each object.
IronPython doesn’t support the
++
or
--
operators that are supported by Visual Basic for increment and
decrement. Consequently, the class provides an
Inc()
and
Dec()
method. Notice that these methods
aren’t defined as
Shared
because they work with a single object. You need to consider the differences
between binary (those that work with two objects) and unary (those that work with a single object)
operators when creating your extension. Binary operators are always declared as
Shared
, while unary
operators appear as a standard method.
At this point, you can compile the class if desired. Start a copy of the IronPython console and type
the following commands to load the extension.
import clr
clr.AddReferenceToFile(‘Calcs.DLL’)
import Calcs
dir(Calcs.Calcs)
The
dir()
function shows the content of the
Calcs
extension as shown in Figure 17-2. Notice that
Inc()
and
Dec()
appear as you expect. However, there aren’t any entries for
+
,
-
,
*
, and
/
methods.
These operators still work as you expect, but IronPython shows a Python equivalent for the operators
in the form of
__add__()
,
__radd__()
,
__sub__()
,
__rsub__()
,
__mul__()
,
__rmul__()
,
__div__
()
, and
__rdiv__()
. These methods don’t appear unless you define the operators in your class.
If you’re looking at the class in the IronPython console, you might want to give it a quick try before
you close up the console and move on to the next part of the example. Try this code and you’ll see
an output of 15 from the
__add__()
method. Figure 17-2 shows the results of the calculation.
Value1 = Calcs.Calcs(10)
Value2 = Calcs.Calcs(5)
print Value1.__add__(Value2)
548592c17.indd 363
2/24/10 12:49:33 PM
www.finebook.ir
Do'stlaringiz bilan baham: |