string szElement = "insert-me"; ArrayList szArray = new ArrayList (); szArray.Add (szElement);
要检索现有的元素,请将所需元素的索引传递给 Item() 方法。另外,作为一种简写形式,还可以使用方括号 operator [],它实际上映射到 Item() 方法。
Console.WriteLine (szArray[2]); Console.WriteLine (szArray.Item (2));
ArrayList 类中还有许多其他方法,但是插入和检索都是我们需要在此示例中使用的。请查阅 MSDN 库以获得完整的参考指南。
步骤 6. 文件输入/输出 现在,让我们来实现读取输入文件和写入输出文件。我们将每一行读取到一个字符串数组中,然后输出该字符串数组。在下一步中,我们将使用 QuickSort 算法来对该数组进行排序。
修改源代码 更改 C# 源文件 (class1.cs),如下面以斜体突出显示的代码所示。其他的差异(如类名)可忽略不计。
// Import namespaces using System; using System.Collections; using System.IO; // Declare namespace namespace MsdnAA { // Declare application class class QuickSortApp { // Application initialization static void Main (string[] szArgs) { ... ... ... // Read contents of source file string szSrcLine; ArrayList szContents = new ArrayList (); FileStream fsInput = new FileStream (szSrcFile, FileMode.Open, FileAccess.Read); StreamReader srInput = new StreamReader (fsInput); while ((szSrcLine = srInput.ReadLine ()) != null) { // Append to array szContents.Add (szSrcLine); } srInput.Close (); fsInput.Close (); // TODO: Pass to QuickSort function // Write sorted lines FileStream fsOutput = new FileStream (szDestFile, FileMode.Create, FileAccess.Write); StreamWriter srOutput = new StreamWriter (fsOutput); for (int nIndex = 0; nIndex < szContents.Count; nIndex++) { // Write line to output file srOutput.WriteLine (szContents[nIndex]); } srOutput.Close (); fsOutput.Close (); // Report program success Console.WriteLine ("\nThe sorted lines have been written.\n\n"); } } }
从源文件进行读取 使用 FileStream 类打开源文件,然后加入 StreamReader 类,这样我们就可以使用它的 ReadLine() 方法了。现在,我们调用 ReadLine() 方法,直到它返回 null,这表示到达文件结尾。在循环过程中,我们将读取的行存储到字符串数组中,然后关闭这两个对象。
写入输出文件 假设已经用 QuickSort 对字符串数组进行了排序,接下来要做的事情就是输出数组的内容。按照同样的方式,我们将 StreamWriter 对象附加到 FileStream 对象上。这使得我们可以使用 WriteLine() 方法,该方法能够很方便地模仿 Console 类的行为。一旦遍历了数组,我们便可以象前面一样关闭这两个对象。
步骤 7. 创建函数 最后一步就是创建一个函数来在字符串数组中运行 QuickSort。我们将此函数放到应用程序类 QuickSortApp 之中。
修改源代码 更改 C# 源文件 (class1.cs),如下面以斜体突出显示的 代码所示。其他的差异(如类名)可忽略不计。
// Import namespaces using System; using System.Collections; using System.IO; // Declare namespace namespace MsdnAA { // Declare application class class QuickSortApp { // Application initialization static void Main (string[] szArgs) { ... ... ... // Pass to QuickSort function QuickSort (szContents, 0, szContents.Count - 1); ... ... ... } // QuickSort implementation static void QuickSort (ArrayList szArray, int nLower, int nUpper) { // Check for non-base case if (nLower < nUpper) { // Split and sort partitions int nSplit = Partition (szArray, nLower, nUpper);本教程共 6页,当前在第 3页 1 2 3 4 5 6
|