• 2022年7月31日--使用C#迈出第一步--使用 C# 创建具有约定、空格和注释的易读代码


    编写易于阅读、更新并支持使用命名约定、注释和空格的代码。

    简介

    选择遵循规则和约定的变量名称

    一位软件开发人员曾经说过一句名言:“软件开发最难的部分就是命名。”变量的名称不仅必须遵循某些语法规则,还应使代码更易于用户阅读和理解。 编写一行代码的要求非常多!

    变量名称规则

    C# 编译器强制执行一些变量名称规则。

    变量名称规则

    • 变量名可包含字母数字字符和下划线字符。 不允许使用特殊字符(如英镑 #、短划线 - 或美元符号 $)。
    • 变量名称必须以字母或下划线开头,不能以数字开头。 开发者将下划线用于特殊目的,因此现在请勿使用。
    • 变量名不能是 C# 关键字。 例如,不允许使用以下变量名称声明:float float; 或 string string;
    • 变量名称区分大小写,这意味着 string MyValue; 和 string myValue; 是两个不同的变量。

    变量名称约定

    • 变量名称应使用驼峰式大小写形式,这是一种编写样式,即第一个单词以小写字母开始,后续每个单词的首字母采用大写形式。 例如:string thisIsCamelCase;
    • 变量名称在应用程序中应具有描述性且有意义。 应为变量选择一个名称,用于表示其将保存的数据类型。
    • 变量名称应是附加在一起的一个或多个完整单词。 请勿使用缩写,因为阅读你代码的人可能不清楚该变量的名称。
    • 变量名称不应包含变量的数据类型。 你可能会看到使用类似 string strMyValue; 样式的一些建议。 这是几年前的热门样式。 但是,大多数开发者不会再遵循此建议。

    变量名称示例

    1. char userOption;
    2. int gameScore;
    3. float particlesPerMillion;
    4. bool processedCustomer;

    其他命名约定

    练习-注释代码

    什么是代码注释?

    代码注释是一条指令,用于指示编译器忽略当前行中代码注释符号后面的一切内容。

    以下三种情况非常有用:

    • 当你想记下一段代码的意图时。 当你准备编写一组极具挑战性的代码指令时,这有助于描述用途或思考过程。 将来的你会感谢自己。
    • 当你想暂时删除应用程序中的代码,以尝试其他方法,但不确信新想法是否有用时。 可以注释掉代码,编写新代码,一旦你确定新代码会按预期方式运行时,就可安全地删除旧代码(注释代码)。
    • 添加类似于 TODO 的消息,以提醒自己稍后查看特定的代码段。 你应该明智地使用此消息,这是一个有效原因。 当阅读到引起你关注的代码行时,你可能正在使用另一项功能。 你可以对其进行标记以便稍后调查,而不是忽略关注的新代码行。 Visual Studio IDE 甚至提供名为“任务列表”的窗口,以帮助你识别你在代码中记下的 TODO 消息。

    备注

    代码注释不可信任。 通常,开发者会更新其代码,但忘记更新代码注释。 最好使用注释来描述更高级别的想法,请勿添加关于单个代码行如何工作的注释。

    步骤1-在.NET编辑器中添加一些代码,作为本练习的起点

    1. string firstName = "Bob";
    2. int widgetsSold = 7;
    3. Console.WriteLine($"{firstName} sold {widgetsSold} widgets.");

    步骤2-注释掉上一个练习中的代码行

    1. string firstName = "Bob";
    2. int widgetsPurchased = 7;
    3. // Testing a change to the message.
    4. // int widgetsSold = 7;
    5. // Console.WriteLine($"{firstName} sold {widgetsSold} widgets.");
    6. Console.WriteLine($"{firstName} purchased {widgetsPurchased} widgets.");

    Bob purchased 7 widgets.

    请注意,代码注释用于记录可能做出的更改,并用于在我们测试新消息时暂时禁用旧消息。 如果我们对新代码感到满意,可以安全地删除注释掉的旧代码。在我们确信准备永久删除工作代码之前,这是一种修改工作代码的更安全、更有条理的方法。

    步骤3-删除注释掉的代码

    1. string firstName = "Bob";
    2. int widgetsPurchased = 7;
    3. Console.WriteLine($"{firstName} purchased {widgetsPurchased} widgets.");

    步骤4-使用多行注释

    编写较长的注释或删除多个代码行,可以通过将 /* 添加到代码开头,将 */ 添加到结尾来注释多行。

    1. /*
    2. string firstName = "Bob";
    3. int widgetsPurchased = 7;
    4. Console.WriteLine($"{firstName} purchased {widgetsPurchased} widgets.");
    5. */

    使用多行注释是禁用三个或以上代码行的最快速、最简单的方式。

    步骤5-删除.NET编辑器中的所有代码

    步骤6-将注释质量不佳的代码添加到.NET编辑器

    1. Random random = new Random();
    2. string[] orderIDs = new string[5];
    3. // Loop through each blank orderID
    4. for (int i = 0; i < orderIDs.Length; i++)
    5. {
    6. // Get a random value that equates to ASCII letters A through E
    7. int prefixValue = random.Next(65, 70);
    8. // Convert the random value into a char, then a string
    9. string prefix = Convert.ToChar(prefixValue).ToString();
    10. // Create a random number, padd with zeroes
    11. string suffix = random.Next(1, 1000).ToString("000");
    12. // Combine the prefix and suffix together, then assign to current OrderID
    13. orderIDs[i] = prefix + suffix;
    14. }
    15. // Print out each orderID
    16. foreach (var orderID in orderIDs)
    17. {
    18. Console.WriteLine(orderID);
    19. }

    步骤7-删除低级别的描述性注释

    1. Random random = new Random();
    2. string[] orderIDs = new string[5];
    3. for (int i = 0; i < orderIDs.Length; i++)
    4. {
    5. int prefixValue = random.Next(65, 70);
    6. string prefix = Convert.ToChar(prefixValue).ToString();
    7. string suffix = random.Next(1, 1000).ToString("000");
    8. orderIDs[i] = prefix + suffix;
    9. }
    10. foreach (var orderID in orderIDs)
    11. {
    12. Console.WriteLine(orderID);
    13. }

    步骤8-添加代码注释以解释代码的更高级别用途

    1. /*
    2. The following code creates five random OrderIDs
    3. to test the fraud detection process. OrderIDs
    4. consist of a letter from A to E, and a three
    5. digit number. Ex. A123.
    6. */
    7. Random random = new Random();
    8. string[] orderIDs = new string[5];
    9. for (int i = 0; i < orderIDs.Length; i++)
    10. {
    11. int prefixValue = random.Next(65, 70);
    12. string prefix = Convert.ToChar(prefixValue).ToString();
    13. string suffix = random.Next(1, 1000).ToString("000");
    14. orderIDs[i] = prefix + suffix;
    15. }
    16. foreach (var orderID in orderIDs)
    17. {
    18. Console.WriteLine(orderID);
    19. }

    概括

    • 使用代码注释为自己添加有意义的备注,注明代码可解决的问题。
    • 请勿使用解释 C# 或 .NET 类库如何工作的代码注释。
    • 暂时尝试替代解决方法时,请使用代码注释,直至你已准备提交新的代码解决方案,此时可以删除旧代码。
    • 不要完全相信注释。 在进行许多更改和更新之后,它们可能不会反映代码的当前状态。

    练习-使用空格

    平面设计师和网页设计师知道,在较小的空间中放入过多信息会使观看者不知所措。 因此,他们战略性地使用空格或负空间来分散信息,以最大程度地使观看者能够消化其作品中的主要消息。

    当开发者在编辑器中编写代码时,他们可以使用类似的策略。 通过使用空格传达含义,开发者可以更清楚地传达代码意图。

    什么是空格?

    术语“空格”指的是由 space bar 生成的单个空格、由 tab 键生成的制表符以及由 enter 键生成的新行。

    C# 编译器会忽略空格。

    步骤1-添加代码以说明C#编译器如何忽略空格

    1. // Example 1:
    2. Console
    3. .
    4. WriteLine
    5. (
    6. "Hello World!"
    7. )
    8. ;
    9. // Example 2:
    10. string firstWord="Hello";string lastWord="World";Console.WriteLine(firstWord+" "+lastWord+"!");

    步骤2-运行代码以查看输出

    1. Hello World!
    2. Hello World!

    • 每个完整的命令(语句)都属于单独的一行。
    • 如果单个代码行过长,可以将其拆分。 但是,不应随意将单个语句拆分为多行,除非你有充分的理由这样做。
    • 在赋值运算符的左侧和右侧使用空格。

    步骤3-删除.NET编辑器中的所有代码

    1. Random dice = new Random();
    2. int roll1 = dice.Next(1, 7);
    3. int roll2 = dice.Next(1, 7);
    4. int roll3 = dice.Next(1, 7);
    5. int total = roll1 + roll2 + roll3;
    6. Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
    7. if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3)) {
    8. if ((roll1 == roll2) && (roll2 == roll3)) {
    9. Console.WriteLine("You rolled triples! +6 bonus to total!");
    10. total += 6;
    11. } else {
    12. Console.WriteLine("You rolled doubles! +2 bonus to total!");
    13. total += 2;
    14. }
    15. }

    Dice roll: 1 + 3 + 5 = 9

    步骤4-添加代码以开始练习的下一个部分

    1. Random dice = new Random();
    2. int roll1 = dice.Next(1, 7);
    3. int roll2 = dice.Next(1, 7);
    4. int roll3 = dice.Next(1, 7);
    5. int total = roll1 + roll2 + roll3;
    6. Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
    7. if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3)) {
    8. if ((roll1 == roll2) && (roll2 == roll3)) {
    9. Console.WriteLine("You rolled triples! +6 bonus to total!");
    10. total += 6;
    11. } else {
    12. Console.WriteLine("You rolled doubles! +2 bonus to total!");
    13. total += 2;
    14. }
    15. }

    步骤5-添加空格以创建表述并提高可读性

    1. Random dice = new Random();
    2. int roll1 = dice.Next(1, 7);
    3. int roll2 = dice.Next(1, 7);
    4. int roll3 = dice.Next(1, 7);
    5. int total = roll1 + roll2 + roll3;
    6. Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
    7. if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3)) {
    8. if ((roll1 == roll2) && (roll2 == roll3)) {
    9. Console.WriteLine("You rolled triples! +6 bonus to total!");
    10. total += 6;
    11. } else {
    12. Console.WriteLine("You rolled doubles! +2 bonus to total!");
    13. total += 2;
    14. }
    15. }

    步骤6-将左大括号和右大括号移动到其自己的行,以增加间距

    1. Random dice = new Random();
    2. int roll1 = dice.Next(1, 7);
    3. int roll2 = dice.Next(1, 7);
    4. int roll3 = dice.Next(1, 7);
    5. int total = roll1 + roll2 + roll3;
    6. Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
    7. if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
    8. {
    9. if ((roll1 == roll2) && (roll2 == roll3))
    10. {
    11. Console.WriteLine("You rolled triples! +6 bonus to total!");
    12. total += 6;
    13. }
    14. else
    15. {
    16. Console.WriteLine("You rolled doubles! +2 bonus to total!");
    17. total += 2;
    18. }
    19. }

    概括

    • 明智地使用空格来提高代码的可读性。
    • 使用换行符来创建空行以分隔代码短语。 一个短语由类似或协同工作的代码行组成。
    • 使用换行符分隔代码块符号,使其处于自己的代码行中。
    • 使用 tab 键将代码块与相关的关键字对齐。
    • 缩进代码块中的代码以显示所有权。

    挑战

    步骤1-删除前述练习中.NET编辑器内的所有代码

    步骤2-在.NET编辑器从以下不可读代码开始

    1. string str = "The quick brown fox jumps over the lazy dog.";
    2. // convert the message into a char array
    3. char[] charMessage = str.ToCharArray();
    4. // Reverse the chars
    5. Array.Reverse(charMessage);
    6. int x = 0;
    7. // count the o's
    8. foreach (char i in charMessage) { if (i == 'o') { x++; } }
    9. // convert it back to a string
    10. string new_message = new String(charMessage);
    11. // print it out
    12. Console.WriteLine(new_message);
    13. Console.WriteLine($"'o' appears {x} times.");

    1. .god yzal eht revo spmuj xof nworb kciuq ehT
    2. 'o' appears 4 times.

    步骤3-修改代码以提高其可读性

    解决方案

    1. /*
    2. This code reverses a message, counts the number of times
    3. a particular character appears, then prints the results
    4. to the console window.
    5. */
    6. string originalMessage = "The quick brown fox jumps over the lazy dog.";
    7. char[] message = originalMessage.ToCharArray();
    8. Array.Reverse(message);
    9. int letterCount = 0;
    10. foreach (char letter in message)
    11. {
    12. if (letter == 'o')
    13. {
    14. letterCount++;
    15. }
    16. }
    17. string newMessage = new String(message);
    18. Console.WriteLine(newMessage);
    19. Console.WriteLine($"'o' appears {letterCount} times.");

  • 相关阅读:
    基于C++实现⾃然连接操作算法
    emqx 集群搭建
    Linux 中的 chpasswd 命令及示例
    CSRF 漏洞详解
    webpack loader 用于对模块的源代码进行转换
    【Swift 60秒】01 - Variables - 变量
    「Kafka」监控、集成篇
    Sqoop数据导入 第3关:Mysql导入数据至Hive中
    为忙碌的软件工程师精心准备的编码面试准备材料,超过 100,000 人受益!
    UWB室内定位技术
  • 原文地址:https://blog.csdn.net/DXB2021/article/details/126087390