Working with Generics
❘
135
list of directories using
MyDir.GetDirectories()
and a list of files using
MyDir.GetFiles()
. In
this case, the code simply prints out the result, but you could go on to process the directories and
files. Figure 7-14 shows typical output from this example (of course, the actual directory and file-
names will match your system).
FIguRE 7-14:
A list of directories and subdirectories is in the C:\ folder.
WoRkINg WITH gENERICS
Generic classes are exceptionally easy to work with in IronPython, which is a good feature to have
because the .NET Framework includes a lot of generic classes. Listing 7-5 starts with a simple
List
,
but the technique shown in this listing works with every other generic class that .NET provides.
lISTINg 7-5:
Using .NET generics
# Add the .NET Framework 2.0 to the path.
import sys
sys.path.append(‘C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727’)
# Make clr accessible.
import clr
# Import the required assemblies.
import System
continues
548592c07.indd 135
2/25/10 9:44:30 AM
www.finebook.ir
136
❘
CHAPTER 7
Accessing the .net FrAmework
import System.Collections.Generic
# Create an integer list.
MyList = System.Collections.Generic.List[int]()
# Add items to the list.
MyList.Add(1)
MyList.Add(2)
MyList.Add(3)
# Enumerate the list.
print ‘Initial List’
for I in MyList:
print I,
# Add a range of numbers.
MyList.AddRange(range(5))
# Enumerate the updated list.
print ‘\n\nList With Range Added’
for I in MyList:
print I,
# Remove a value that’s no longer needed.
MyList.Remove(4)
# Display the results.
print ‘\n\nList With 4 Removed’
for I in MyList:
print I,
# Remove a range of items.
MyList.RemoveRange(1, 2)
# Display the results.
print ‘\n\nRemoved Items 1 and 2’
for I in MyList:
print I,
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
The code begins with the usual imports. Notice that you must import
System.Collections.Generic
to make this example work. If you were going to work quite a bit with this namespace, you’d want to
import it into the global namespace because typing the longer namespace would prove time consuming
and error prone. Fortunately, you use it only once in this example, to create
MyList
, which is an
int
List
. Notice that the data type of
List
appears within square brackets and that the example uses
a Python data type. You could just as easily use a .NET data type.
lISTINg 7-5
(continued)
548592c07.indd 136
2/25/10 9:44:31 AM
www.finebook.ir
Do'stlaringiz bilan baham: |