源代码注释 字符 // 将行的剩余部分标记为一个注释,这样 C# 编译器就会忽略它。另外,/* 和 */ 之间的代码也会被当作注释。
// This line is ignored by the compiler. /* This block of text is also ignored by the Visual C# compiler. */
Using 指令 .NET 框架为开发人员提供了许多有用的类。例如,Console 类处理对控制台窗口的输入和输出。这些类是按照层次树的形式组织的。Console 类的完全限定名实际上是 System.Console。其他的类包括 System.IO.FileStream 和 System.Collections.Queue。
using 指令允许您在不使用完全限定名的情况下引用命名空间中的类。以斜体突出显示的 代码应用了 using 指令。
using System; class Class1 { static void Main(string[] args) { System.Console.WriteLine ("Hello, C#.NET World!"); Console.WriteLine ("Hello, C#.NET World!"); } }
类声明 与 C++ 或 Visual Basic 不同,Visual C# 中的所有函数都必须封装在一个类中。class 语句声明一个新的 C# 类。就 Hello World 应用程序来说,Class1 类包含一个函数,即 Main() 函数。如果用一个 namespace 块将类的定义括起来,就可以把类组织为诸如 MsdnAA.QuickSortApp 这样的层次。
在本入门指南中,我们并不打算深入地介绍类,但是我们将为您简要概述为什么类是我们的示例应用程序的一部分。
Main() 函数 在应用程序加载到内存之后,Main() 函数就会接收控制,因此,应该将应用程序启动代码放在此函数中。传递给程序的命令行参数存储在 args 字符串数组中。
步骤 4. 控制台输入 现在,我们将继续编写 QuickSort 应用程序。我们需要做的第一件事就是提示用户提供输入和输出文件。
修改源代码 更改 C# 源文件 (class1.cs),如下面以斜体突出显示的代码所示。其他的差异(如类名)可忽略不计。
// Import namespaces using System; // Declare namespace namespace MsdnAA { // Declare application class class QuickSortApp { // Application initialization static void Main (string[] szArgs) { // Describe program function Console.WriteLine ("QuickSort C#.NET Sample Application\n"); // Prompt user for filenames Console.Write ("Source: "); string szSrcFile = Console.ReadLine (); Console.Write ("Output: "); string szDestFile = Console.ReadLine (); } } }
从控制台进行读取 Console 类的 ReadLine() 方法提示用户输入,并返回输入的字符串。它会自动地为字符串处理内存分配,由于使用了 .NET 垃圾回收器,您不需要做任何释放内存的工作。
程序输出 从菜单中选择 Debug | Start Without Debugging 来运行程序。这是到此为止来自 QuickSort 应用程序的输出的屏幕截图。
步骤 5. 使用数组 在对从输入读取的行进行排序之前,程序需要将其存储到一个数组中。我们将简要讨论可实现对象数组的 .NET 基类的用法。
修改源代码 更改 C# 源文件 (class1.cs),如下面以斜体突出显示的代码所示。其他的差异(如类名)可忽略不计。
// Import namespaces using System; using System.Collections; // Declare namespace namespace MsdnAA { // Declare application class class QuickSortApp { // Application initialization static void Main (string[] szArgs) { // Describe program function Console.WriteLine ("QuickSort C#.NET Sample Application\n"); // Prompt user for filenames Console.Write ("Source: "); string szSrcFile = Console.ReadLine (); Console.Write ("Output: "); string szDestFile = Console.ReadLine (); // TODO: Read contents of source file ArrayList szContents = new ArrayList (); } } }
使用 ArrayList 类 我们将导入 System.Collections 命名空间,这样我们就可以直接引用 ArrayList。此类实现大小可动态调整的对象数组。要插入新的元素,可以简单地将对象传递到 ArrayList 类的 Add() 方法。新的数组元素将引用原始的对象,而垃圾回收器将处理它的释放。本教程共 6页,当前在第 2页 1 2 3 4 5 6
|