编写易于阅读、更新并支持使用命名约定、注释和空格的代码。
一位软件开发人员曾经说过一句名言:“软件开发最难的部分就是命名。”变量的名称不仅必须遵循某些语法规则,还应使代码更易于用户阅读和理解。 编写一行代码的要求非常多!
C# 编译器强制执行一些变量名称规则。
变量名称规则
#、短划线 - 或美元符号 $)。float float; 或 string string;。string MyValue; 和 string myValue; 是两个不同的变量。
string thisIsCamelCase;。string strMyValue; 样式的一些建议。 这是几年前的热门样式。 但是,大多数开发者不会再遵循此建议。
- char userOption;
-
- int gameScore;
-
- float particlesPerMillion;
-
- bool processedCustomer;
代码注释是一条指令,用于指示编译器忽略当前行中代码注释符号后面的一切内容。
以下三种情况非常有用:
TODO 的消息,以提醒自己稍后查看特定的代码段。 你应该明智地使用此消息,这是一个有效原因。 当阅读到引起你关注的代码行时,你可能正在使用另一项功能。 你可以对其进行标记以便稍后调查,而不是忽略关注的新代码行。 Visual Studio IDE 甚至提供名为“任务列表”的窗口,以帮助你识别你在代码中记下的 TODO 消息。
备注
代码注释不可信任。 通常,开发者会更新其代码,但忘记更新代码注释。 最好使用注释来描述更高级别的想法,请勿添加关于单个代码行如何工作的注释。
- string firstName = "Bob";
- int widgetsSold = 7;
- Console.WriteLine($"{firstName} sold {widgetsSold} widgets.");
- string firstName = "Bob";
- int widgetsPurchased = 7;
- // Testing a change to the message.
- // int widgetsSold = 7;
- // Console.WriteLine($"{firstName} sold {widgetsSold} widgets.");
- Console.WriteLine($"{firstName} purchased {widgetsPurchased} widgets.");
Bob purchased 7 widgets.
请注意,代码注释用于记录可能做出的更改,并用于在我们测试新消息时暂时禁用旧消息。 如果我们对新代码感到满意,可以安全地删除注释掉的旧代码。在我们确信准备永久删除工作代码之前,这是一种修改工作代码的更安全、更有条理的方法。
- string firstName = "Bob";
- int widgetsPurchased = 7;
- Console.WriteLine($"{firstName} purchased {widgetsPurchased} widgets.");
编写较长的注释或删除多个代码行,可以通过将 /* 添加到代码开头,将 */ 添加到结尾来注释多行。
- /*
- string firstName = "Bob";
- int widgetsPurchased = 7;
- Console.WriteLine($"{firstName} purchased {widgetsPurchased} widgets.");
- */
使用多行注释是禁用三个或以上代码行的最快速、最简单的方式。
- Random random = new Random();
- string[] orderIDs = new string[5];
- // Loop through each blank orderID
- for (int i = 0; i < orderIDs.Length; i++)
- {
- // Get a random value that equates to ASCII letters A through E
- int prefixValue = random.Next(65, 70);
- // Convert the random value into a char, then a string
- string prefix = Convert.ToChar(prefixValue).ToString();
- // Create a random number, padd with zeroes
- string suffix = random.Next(1, 1000).ToString("000");
- // Combine the prefix and suffix together, then assign to current OrderID
- orderIDs[i] = prefix + suffix;
- }
- // Print out each orderID
- foreach (var orderID in orderIDs)
- {
- Console.WriteLine(orderID);
- }
- Random random = new Random();
- string[] orderIDs = new string[5];
-
- for (int i = 0; i < orderIDs.Length; i++)
- {
- int prefixValue = random.Next(65, 70);
- string prefix = Convert.ToChar(prefixValue).ToString();
- string suffix = random.Next(1, 1000).ToString("000");
-
- orderIDs[i] = prefix + suffix;
- }
-
- foreach (var orderID in orderIDs)
- {
- Console.WriteLine(orderID);
- }
- /*
- The following code creates five random OrderIDs
- to test the fraud detection process. OrderIDs
- consist of a letter from A to E, and a three
- digit number. Ex. A123.
- */
- Random random = new Random();
- string[] orderIDs = new string[5];
-
- for (int i = 0; i < orderIDs.Length; i++)
- {
- int prefixValue = random.Next(65, 70);
- string prefix = Convert.ToChar(prefixValue).ToString();
- string suffix = random.Next(1, 1000).ToString("000");
-
- orderIDs[i] = prefix + suffix;
- }
-
- foreach (var orderID in orderIDs)
- {
- Console.WriteLine(orderID);
- }
平面设计师和网页设计师知道,在较小的空间中放入过多信息会使观看者不知所措。 因此,他们战略性地使用空格或负空间来分散信息,以最大程度地使观看者能够消化其作品中的主要消息。
当开发者在编辑器中编写代码时,他们可以使用类似的策略。 通过使用空格传达含义,开发者可以更清楚地传达代码意图。
术语“空格”指的是由 space bar 生成的单个空格、由 tab 键生成的制表符以及由 enter 键生成的新行。
C# 编译器会忽略空格。
- // Example 1:
- Console
- .
- WriteLine
- (
- "Hello World!"
- )
- ;
-
- // Example 2:
- string firstWord="Hello";string lastWord="World";Console.WriteLine(firstWord+" "+lastWord+"!");
- Hello World!
- Hello World!
- Random dice = new Random();
- int roll1 = dice.Next(1, 7);
- int roll2 = dice.Next(1, 7);
- int roll3 = dice.Next(1, 7);
- int total = roll1 + roll2 + roll3;
- Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
- if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3)) {
- if ((roll1 == roll2) && (roll2 == roll3)) {
- Console.WriteLine("You rolled triples! +6 bonus to total!");
- total += 6;
- } else {
- Console.WriteLine("You rolled doubles! +2 bonus to total!");
- total += 2;
- }
- }
Dice roll: 1 + 3 + 5 = 9
- Random dice = new Random();
-
- int roll1 = dice.Next(1, 7);
- int roll2 = dice.Next(1, 7);
- int roll3 = dice.Next(1, 7);
-
- int total = roll1 + roll2 + roll3;
- Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
-
- if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3)) {
- if ((roll1 == roll2) && (roll2 == roll3)) {
- Console.WriteLine("You rolled triples! +6 bonus to total!");
- total += 6;
- } else {
- Console.WriteLine("You rolled doubles! +2 bonus to total!");
- total += 2;
- }
- }
- Random dice = new Random();
-
- int roll1 = dice.Next(1, 7);
- int roll2 = dice.Next(1, 7);
- int roll3 = dice.Next(1, 7);
-
- int total = roll1 + roll2 + roll3;
- Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
-
- if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3)) {
- if ((roll1 == roll2) && (roll2 == roll3)) {
- Console.WriteLine("You rolled triples! +6 bonus to total!");
- total += 6;
- } else {
- Console.WriteLine("You rolled doubles! +2 bonus to total!");
- total += 2;
- }
- }
- Random dice = new Random();
-
- int roll1 = dice.Next(1, 7);
- int roll2 = dice.Next(1, 7);
- int roll3 = dice.Next(1, 7);
-
- int total = roll1 + roll2 + roll3;
- Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
-
- if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
- {
- if ((roll1 == roll2) && (roll2 == roll3))
- {
- Console.WriteLine("You rolled triples! +6 bonus to total!");
- total += 6;
- }
- else
- {
- Console.WriteLine("You rolled doubles! +2 bonus to total!");
- total += 2;
- }
- }
tab 键将代码块与相关的关键字对齐。
- string str = "The quick brown fox jumps over the lazy dog.";
- // convert the message into a char array
- char[] charMessage = str.ToCharArray();
- // Reverse the chars
- Array.Reverse(charMessage);
- int x = 0;
- // count the o's
- foreach (char i in charMessage) { if (i == 'o') { x++; } }
- // convert it back to a string
- string new_message = new String(charMessage);
- // print it out
- Console.WriteLine(new_message);
- Console.WriteLine($"'o' appears {x} times.");
- .god yzal eht revo spmuj xof nworb kciuq ehT
- 'o' appears 4 times.
- /*
- This code reverses a message, counts the number of times
- a particular character appears, then prints the results
- to the console window.
- */
-
- string originalMessage = "The quick brown fox jumps over the lazy dog.";
-
- char[] message = originalMessage.ToCharArray();
- Array.Reverse(message);
-
- int letterCount = 0;
-
- foreach (char letter in message)
- {
- if (letter == 'o')
- {
- letterCount++;
- }
- }
-
- string newMessage = new String(message);
-
- Console.WriteLine(newMessage);
- Console.WriteLine($"'o' appears {letterCount} times.");