118
❘
CHAPTER 7
Accessing the .net FrAmework
begin using generics with a number of examples in the book, but for now you should focus on under-
standing the technique used to work with generics.
ImPoRTINg THE .NET FRAmEWoRk ASSEmblIES
Importing an assembly into IronPython isn’t much different from importing a Python module.
In fact, you use about the same code. The primary difference is that you can’t import some .NET
assemblies directly into IronPython, just as you can’t import them directly into any .NET language.
Instead, you must first create a reference to the .NET assembly and then import it. For anyone who
has worked with .NET languages in the past, nothing will have changed from the normal procedure
they follow.
One odd thing about IronPython is that it’s case sensitive even when it comes to
.NET Framework assemblies. As a consequence, importing
system.math
won’t
work but importing
System.Math
will. Because many developers aren’t used to
thinking about the case of .NET Framework assemblies, you might be caught
off guard when an application fails for some unknown reason. One issue always
to consider is whether you’ve capitalized the assembly name incorrectly.
Performing a Standard Import
As with Python modules, you can perform a standard import of a .NET assembly. For example, you
might want to import the .NET Framework’s
System
assembly.
In this case, you type
import System
and press Enter. If you want to see what the System assembly contains, type
dir(System)
and press Enter. Figure 7-1 shows typical results from importing the
System
assembly.
Now, let’s say that you want to create a
UInt32
variable, just like a
UInt32
that you’d create in any
other .NET language. Simply type something like
MyVar = System.UInt32(5)
. Of course, you can
use any variable within the range that fits within a
UInt32
. If you don’t
provide a value by typing
MyVar = System.UInt32()
the .NET Framework automatically assigns the variable a value of 0. You
can read more about .NET data types in the section “Using .NET Data Types” later in this chapter.
However, let’s take a look at
MyVar
. If you type
MyVar
by itself, you see that it’s
an object that has a
value of 5, as shown in Figure 7-2. Type
dir(MyVar)
and you see that
MyVar
contains many of the
same methods as a standard Python integer. For example, you still have access to the absolute value
function,
__abs__()
,
and comparison method,
__eq__()
. In addition to these standard methods,
you also have access to .NET-specific functions such as
Parse()
and
ToChar()
.
548592c07.indd 118
2/25/10 9:44:26 AM
www.finebook.ir