适用范围: yes Visual Studio no Visual Studio for Mac no Visual Studio Code

在本教程中,你将使用 Visual Studio 创建和运行 C# 控制台应用,并探索 Visual Studio 集成开发环境 (IDE) 的部分功能。 本教程是由两个部分构成的系列教程的第一部分。

本教程介绍以下操作:

  • 创建一个 Visual Studio 项目。
  • 创建一个 C# 控制台应用。
  • 调试应用。
  • 关闭应用。
  • 检查完整的代码。
  • 在第 2 部分 ,你将扩展此应用以添加更多项目、了解调试技巧和引用第三方包。

    必须安装 Visual Studio。

    如果尚未安装 Visual Studio,请转到 Visual Studio 下载 页免费安装。

    若要开始,请创建一个 C# 应用程序项目。 项目类型随附了所需的全部模板文件。

  • 打开 Visual Studio,然后在“开始”窗口中选择“创建新项目”。

  • 在“创建新项目”窗口中,从“语言”列表中选择“C#”。 接下来,从“平台”列表中选择“Windows”,然后从“项目类型”列表中选择“控制台”。

    应用语言、平台和项目类型筛选器之后,选择“控制台应用程序”模板,然后选择“下一步” 。

    如果未看到“控制台应用程序”模板,请选择“安装更多工具和功能” 。

    然后,在 Visual Studio 安装程序中,选择“.NET Core 跨平台开发”工作负载 。

    之后,在 Visual Studio 安装程序中选择“修改”按钮 。 系统可能会提示你保存所有内容;如果出现提示,请按照指示进行操作。 接下来,选择“继续”,以安装工作负载 。 然后,返回到“ 创建项目 ”过程中的步骤 2。

  • 在“配置新项目”窗口中,在“项目名称”框中键入或输入“计算器”。 然后,选择“下一步”。

  • 在“附加信息”窗口中,应已为目标框架选择“.NET Core 3.1” 。 如果未选择,则请选择“.NET Core 3.1”。 然后,选择“创建”。

    Visual Studio 随即打开新项目,其中包含默认的“Hello World”代码。 如果要在编辑器中查看它,可以在“解决方案资源管理器”窗口中选择代码文件“Program.cs”,该窗口通常位于 Visual Studio 的右侧。

    默认“Hello World”代码调用 WriteLine 方法在控制台窗口中显示文本字符串“Hello, World!”。 如果按 F5,则可以在调试模式下运行默认程序。 在调试器中运行应用程序后,控制台窗口将保持打开状态。 按任意键关闭控制台窗口。

  • 在“创建新项目”窗口中选择“所有语言”,然后从下拉列表中选择“C#” 。 从“所有平台”列表中选择“Windows”,然后从“所有项目类型”列表中选择“控制台” 。

    应用语言、平台和项目类型筛选器后,选择“控制台应用”模板,然后选择“下一步” 。

    如果未看到“控制台应用”模板,请选择“安装更多工具和功能” 。

    在 Visual Studio 安装程序中选择“.NET 桌面开发”工作负载,然后选择“修改” 。

  • 在“配置新项目”窗口中,在“项目名称”框中键入“Calculator”,然后选择“下一步” 。

  • 在“其他信息”窗口中,应已选择“.NET 6.0”作为目标框架 。 选择“创建” 。

    Visual Studio 随即打开新项目,其中包含默认的“Hello World”代码。

    如果要在编辑器中查看它,可以在“解决方案资源管理器”窗口中选择代码文件“Program.cs”,该窗口通常位于 Visual Studio 的右侧。

    单个代码语句调用 WriteLine 方法在控制台窗口中显示文本字符串“Hello, World!”。 如果按 F5,则可以在调试模式下运行默认程序。 在调试器中运行应用程序后,控制台窗口将保持打开状态。 按任意键关闭控制台窗口。

    从 .NET 6 开始,使用控制台模板的新项目会生成与以前版本不同的代码。 若要了解详细信息,请参阅 新的 C# 模板生成顶级语句 页。

  • (可选)可以更改运算符来更改结果。 例如,可以将 int c = a + b; 代码行中的 + 运算符更改为 - 进行减法运算,更改为 * 进行乘法运算,或更改为 / 进行除法运算。 然后,运行该程序时,结果也会改变。

  • 关闭控制台窗口。

  • 在“解决方案资源管理器”的右侧窗格中选择“Program.cs”,以在代码编辑器中显示该文件

  • 在代码编辑器中,替换显示了 Console.WriteLine("Hello World!"); 的默认“Hello World”代码。

    将该行替换为以下代码:

        int a = 42;
        int b = 119;
        int c = a + b;
        Console.WriteLine(c);
        Console.ReadKey();
    

    如果你键入代码,则 Visual Studio IntelliSense 功能将提供用于自动完成输入的选项。

  • 若要生成并运行应用,请按 F5,或者在顶部工具栏中选择名称“Calculator”旁边的绿色箭头 。

    随即会打开控制台窗口,其中显示了 42 + 119 的总和,即 161。

  • 关闭控制台窗口。

  • (可选)可以更改运算符来更改结果。 例如,可以将 int c = a + b; 代码行中的 + 运算符更改为 - 进行减法运算,更改为 * 进行乘法运算,或更改为 / 进行除法运算。 运行应用时,结果会相应地更改。

    添加代码以创建计算器

    向项目添加一组更复杂的计算器代码以继续操作。

  • 在代码编辑器中,将 Program.cs 中的所有代码替换为以下新代码:

        using System;
        namespace Calculator
            class Program
                static void Main(string[] args)
                    // Declare variables and then initialize to zero.
                    int num1 = 0; int num2 = 0;
                    // Display title as the C# console calculator app.
                    Console.WriteLine("Console Calculator in C#\r");
                    Console.WriteLine("------------------------\n");
                    // Ask the user to type the first number.
                    Console.WriteLine("Type a number, and then press Enter");
                    num1 = Convert.ToInt32(Console.ReadLine());
                    // Ask the user to type the second number.
                    Console.WriteLine("Type another number, and then press Enter");
                    num2 = Convert.ToInt32(Console.ReadLine());
                    // Ask the user to choose an option.
                    Console.WriteLine("Choose an option from the following list:");
                    Console.WriteLine("\ta - Add");
                    Console.WriteLine("\ts - Subtract");
                    Console.WriteLine("\tm - Multiply");
                    Console.WriteLine("\td - Divide");
                    Console.Write("Your option? ");
                    // Use a switch statement to do the math.
                    switch (Console.ReadLine())
                        case "a":
                            Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
                            break;
                        case "s":
                            Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
                            break;
                        case "m":
                            Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
                            break;
                        case "d":
                            Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
                            break;
                    // Wait for the user to respond before closing.
                    Console.Write("Press any key to close the Calculator console app...");
                    Console.ReadKey();
    
  • 选择“Calculator”按钮或按 F5 运行应用 。

    控制台窗口即会打开。

  • 在控制台窗口中,按照提示将数字 42 和 119 相加 。

    应用应如以下屏幕快照所示:

  • 在代码编辑器中,将 Program.cs 中的所有代码替换为以下新代码:

        // Declare variables and then initialize to zero.
        int num1 = 0; int num2 = 0;
        // Display title as the C# console calculator app.
        Console.WriteLine("Console Calculator in C#\r");
        Console.WriteLine("------------------------\n");
        // Ask the user to type the first number.
        Console.WriteLine("Type a number, and then press Enter");
        num1 = Convert.ToInt32(Console.ReadLine());
        // Ask the user to type the second number.
        Console.WriteLine("Type another number, and then press Enter");
        num2 = Convert.ToInt32(Console.ReadLine());
        // Ask the user to choose an option.
        Console.WriteLine("Choose an option from the following list:");
        Console.WriteLine("\ta - Add");
        Console.WriteLine("\ts - Subtract");
        Console.WriteLine("\tm - Multiply");
        Console.WriteLine("\td - Divide");
        Console.Write("Your option? ");
        // Use a switch statement to do the math.
        switch (Console.ReadLine())
            case "a":
                Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
                break;
            case "s":
                Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
                break;
            case "m":
                Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
                break;
            case "d":
                Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
                break;
        // Wait for the user to respond before closing.
        Console.Write("Press any key to close the Calculator console app...");
        Console.ReadKey();
    
  • 选择“Calculator”按钮或按 F5 运行应用 。

    控制台窗口即会打开。

  • 在控制台窗口中,按照提示将数字 42 和 119 相加 。

    应用应如以下屏幕快照所示:

    现在,应用可以生成小数结果。 对代码再做一些调整,使应用也可以计算小数。

  • 使用“查找和替换”控件将 float 变量的每个实例更改为 double,并将 Convert.ToInt32 方法的每个实例更改为 Convert.ToDouble

  • 运行计算器应用,将数字 42.5 除以数字 119.75 。

    该应用现在接受小数值,并返回更长的小数作为结果。

    修改代码部分,你将减少结果中的小数位数。

    你已改进了基本计算器应用,但该应用目前还不能处理异常,例如用户输入错误。 例如,如果用户尝试除以零或者输入意外的字符,则应用可能会停止工作、返回错误或返回意外的非数值结果。

    现在来演练一些常见的用户输入错误,在调试程序中找到它们(若其出现),并在代码中修复它们。

    有关调试器及其工作原理的详细信息,请参阅初步了解 Visual Studio 调试器

    修复“被零除”错误

    如果你尝试将数字除以零,则控制台应用可能会冻结,并在代码编辑器中显示哪些内容是错误的。

    有时,应用不会冻结且调试器不会显示“被零除”错误。 相反,应用可能会返回意外的非数字结果,如无穷符号。 以下代码修复仍然适用。

    若要更改代码以处理此错误,请执行以下操作:

  • 在 Program.cs 中,将 case "d": 的代码替换为以下代码:

             // Ask the user to enter a non-zero divisor until they do so.
                 while (num2 == 0)
                     Console.WriteLine("Enter a non-zero divisor: ");
                     num2 = Convert.ToInt32(Console.ReadLine());
                 Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
                 break;
    

    替换代码后,包含 switch 语句的部分应如以下屏幕截图所示:

    现在,将任意数字除以零时,该应用会要求输入另一个数字,并且在你提供非零数字之前,它会不断地要求你这样做。

    修复“格式”错误

    如果在应用要求输入数字字符时你输入了字母字符,应用将会冻结。 Visual Studio 将显示代码编辑器中的哪些内容是错误的。

    可将应用分为两个类:CalculatorProgram,而不是依赖于 program 类来处理所有代码。

    Calculator 类处理大量的计算工作,而 Program 类则会处理用户界面和错误处理工作。

    现在就开始吧。

  • 在 Program.cs 中,删除所有内容并添加以下新的 Calculator 类:

    class Calculator
        public static double DoOperation(double num1, double num2, string op)
            double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error.
            // Use a switch statement to do the math.
            switch (op)
                case "a":
                    result = num1 + num2;
                    break;
                case "s":
                    result = num1 - num2;
                    break;
                case "m":
                    result = num1 * num2;
                    break;
                case "d":
                    // Ask the user to enter a non-zero divisor.
                    if (num2 != 0)
                        result = num1 / num2;
                    break;
                // Return text for an incorrect option entry.
                default:
                    break;
            return result;
    
  • 另外还添加新的 Program 类,如下所示:

    class Program
        static void Main(string[] args)
            bool endApp = false;
            // Display title as the C# console calculator app.
            Console.WriteLine("Console Calculator in C#\r");
            Console.WriteLine("------------------------\n");
            while (!endApp)
                // Declare variables and set to empty.
                string numInput1 = "";
                string numInput2 = "";
                double result = 0;
                // Ask the user to type the first number.
                Console.Write("Type a number, and then press Enter: ");
                numInput1 = Console.ReadLine();
                double cleanNum1 = 0;
                while (!double.TryParse(numInput1, out cleanNum1))
                    Console.Write("This is not valid input. Please enter an integer value: ");
                    numInput1 = Console.ReadLine();
                // Ask the user to type the second number.
                Console.Write("Type another number, and then press Enter: ");
                numInput2 = Console.ReadLine();
                double cleanNum2 = 0;
                while (!double.TryParse(numInput2, out cleanNum2))
                    Console.Write("This is not valid input. Please enter an integer value: ");
                    numInput2 = Console.ReadLine();
                // Ask the user to choose an operator.
                Console.WriteLine("Choose an operator from the following list:");
                Console.WriteLine("\ta - Add");
                Console.WriteLine("\ts - Subtract");
                Console.WriteLine("\tm - Multiply");
                Console.WriteLine("\td - Divide");
                Console.Write("Your option? ");
                string op = Console.ReadLine();
                    result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
                    if (double.IsNaN(result))
                        Console.WriteLine("This operation will result in a mathematical error.\n");
                    else Console.WriteLine("Your result: {0:0.##}\n", result);
                catch (Exception e)
                    Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
                Console.WriteLine("------------------------\n");
                // Wait for the user to respond before closing.
                Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
                if (Console.ReadLine() == "n") endApp = true;
                Console.WriteLine("\n"); // Friendly linespacing.
            return;
    
  • 选择“Calculator”按钮或按 F5 运行应用 。

  • 按照提示,用数字 42 除以数字 119 。 结果应类似于以下屏幕截图:

    添加 Git 源代码管理

    现在你已经创建了应用,可能需要将它添加到 Git 存储库。 Visual Studio 通过 Git 工具简化了该过程,你可直接从 IDE 中使用这些工具。

    Git 是使用最广泛的新式版本控制系统,因此无论你是专业开发人员,还是正在学习如何编码,Git 都非常有用。 如果你是刚刚接触 Git,可访问 https://git-scm.com/ 网站开始了解。 在这里,你能找到速查表、畅销在线图书和 Git 基础知识视频。

    若要将代码与 Git 关联,需要首先创建一个新的 Git 存储库来容纳代码:

  • 在 Visual Studio 右下角的状态栏中,选择“添加到源代码管理”,然后选择“Git” 。

  • 在“创建 Git 存储库”对话框中,登录到 GitHub。

    存储库名称根据你的文件夹位置自动填充。 默认情况下,新存储库是专用的,这意味着只有你可以访问它。

    无论存储库是公用的还是专用的,都最好将代码的远程备份安全地存储在 GitHub 上。 即使你不与团队合作,也可使用任意计算机上在远程存储库中访问你的代码。

  • 选择“创建并推送”。

    创建存储库后,状态栏中会显示状态详细信息。

    带箭头的第一个图标显示当前分支中的传出/传入提交数。 可以使用此图标来拉取任何传入提交或推送任何传出提交。 还可选择先查看这些提交。 为此,请选择图标,然后选择“查看传出/传入”。

    带铅笔的第二个图标显示代码的未提交更改数。 可选择此图标,在“Git 更改”窗口中查看这些更改。

    若要详细了解如何在应用中使用 Git,请参阅 Visual Studio 版本控制文档

    查看:代码完成

    在本教程中,你对计算器应用做出了许多更改。 该应用现在可以更高效地处理计算资源,并可处理大多数的用户输入错误。

    以下是完整代码,全部显示在同一个位置:

    class Calculator public static double DoOperation(double num1, double num2, string op) double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error. // Use a switch statement to do the math. switch (op) case "a": result = num1 + num2; break; case "s": result = num1 - num2; break; case "m": result = num1 * num2; break; case "d": // Ask the user to enter a non-zero divisor. if (num2 != 0) result = num1 / num2; break; // Return text for an incorrect option entry. default: break; return result; class Program static void Main(string[] args) bool endApp = false; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); while (!endApp) // Declare variables and set to empty. string numInput1 = ""; string numInput2 = ""; double result = 0; // Ask the user to type the first number. Console.Write("Type a number, and then press Enter: "); numInput1 = Console.ReadLine(); double cleanNum1 = 0; while (!double.TryParse(numInput1, out cleanNum1)) Console.Write("This is not valid input. Please enter an integer value: "); numInput1 = Console.ReadLine(); // Ask the user to type the second number. Console.Write("Type another number, and then press Enter: "); numInput2 = Console.ReadLine(); double cleanNum2 = 0; while (!double.TryParse(numInput2, out cleanNum2)) Console.Write("This is not valid input. Please enter an integer value: "); numInput2 = Console.ReadLine(); // Ask the user to choose an operator. Console.WriteLine("Choose an operator from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); string op = Console.ReadLine(); result = Calculator.DoOperation(cleanNum1, cleanNum2, op); if (double.IsNaN(result)) Console.WriteLine("This operation will result in a mathematical error.\n"); else Console.WriteLine("Your result: {0:0.##}\n", result); catch (Exception e) Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message); Console.WriteLine("------------------------\n"); // Wait for the user to respond before closing. Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: "); if (Console.ReadLine() == "n") endApp = true; Console.WriteLine("\n"); // Friendly linespacing. return;

    继续学习本教程的第二部分:

    教程第 2 部分:扩展和调试 C# 控制台应用

  •