C# 基本语法怎么写?新手入门语法规则有哪些?

文章导读
Previous Quiz Next C# 是一种面向对象的编程语言。在面向对象编程方法论中,程序由各种对象组成,这些对象通过动作相互交互。对象可以执行的动作称为方法。相同类型的对象被称为具有相同的 type,或者说属于同一个 class。
📋 目录
  1. C# 程序的基本结构
  2. C# 语法规则:基础知识
  3. using 关键字
  4. class 关键字
  5. C# 中的注释
  6. 成员变量
  7. 成员函数
  8. 实例化 Class
  9. Identifiers
  10. C# Keywords
A A

C# - 基本语法



Previous
Quiz
Next

C# 是一种面向对象的编程语言。在面向对象编程方法论中,程序由各种对象组成,这些对象通过动作相互交互。对象可以执行的动作称为方法。相同类型的对象被称为具有相同的 type,或者说属于同一个 class。

C# 程序的基本结构

每个 C# 程序都有一个基本结构。这里是一个简单的示例:

示例

例如,我们考虑一个 Rectangle 对象。它具有 length 和 width 等属性。根据设计,它可能需要接受这些属性的值、计算面积以及显示详细信息的方法。

让我们来看看 Rectangle class 的实现,并讨论 C# 基本语法 −

using System;

namespace RectangleApplication {
   class Rectangle {
      
      // 成员变量
      double length;
      double width;
      
      public void Acceptdetails() {
         length = 4.5;    
         width = 3.5;
      }
      public double GetArea() {
         return length * width; 
      }
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }
   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine(); 
      }
   }
}

当上述代码编译并执行时,会产生以下结果 −

Length: 4.5
Width: 3.5
Area: 15.75

C# 语法规则:基础知识

1. 区分大小写

C# 是区分大小写的,这意味着具有不同大小写的变量名被视为不同的变量。

在以下示例中,我们演示了区分大小写:

int Age = 30;
int age = 25;
Console.WriteLine(Age); // Output: 30
Console.WriteLine(age); // Output: 25

2. 每个语句以分号 (;) 结束

C# 中的所有语句必须以分号结束,以表示命令的结束。

在以下示例中,我们展示了分号的使用:

int x = 10;
Console.WriteLine(x); // Output: 10

3. 大括号 {} 定义代码块

大括号将语句分组到函数、循环和条件语句中。

在以下示例中,我们在 if 语句中使用大括号:

int x = 7;
if (x > 5)
{
    Console.WriteLine("x is greater than 5"); // Output: x is greater than 5
}

4. 缩进和空白字符

C# 会忽略多余的空格和换行符,但适当的缩进使代码更易读。

在以下示例中,我们使用缩进来提高可读性:

int x = 5;
int y = 10;
Console.WriteLine(x + y); // Output: 15

using 关键字

任何 C# 程序的第一条语句是

using System;

using 关键字用于在程序中包含 namespace。程序可以包含多个 using 语句。

class 关键字

class 关键字用于声明 class。

C# 中的注释

注释用于解释代码。编译器会忽略注释内容。C# 程序中的多行注释以 /* 开头,并以 */ 结束,如下所示 −

/* 这个程序演示了
C# 编程语言的基本语法 */

单行注释由 '//' 符号表示。例如,

}//end class Rectangle    

成员变量

变量是 class 的属性或数据成员,用于存储数据。在前面的程序中,Rectangle class 有两个成员变量,名为 lengthwidth

成员函数

函数是一组执行特定任务的语句。class 的成员函数在 class 内声明。我们的示例 class Rectangle 包含三个成员函数:AcceptDetailsGetAreaDisplay

实例化 Class

在前面的程序中,class ExecuteRectangle 包含 Main() 方法并实例化了 Rectangle class。

Identifiers

Identifier 是用于标识 class、variable、function 或任何其他用户定义项的名称。在 C# 中命名 class 的基本规则如下 −

  • 名称必须以字母开头,后面可以跟一系列字母、数字 (0 - 9) 或下划线。Identifier 的第一个字符不能是数字。

  • 它不能包含任何嵌入的空格或符号,例如 ? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / 和 \。但是,可以使用下划线 ( _ )。

  • 它不应是 C# keyword。

C# Keywords

Keywords 是预定义给 C# compiler 的保留字。这些 keywords 不能用作 identifiers。但是,如果您想将这些 keywords 用作 identifiers,可以在 keyword 前加上 @ 字符。

在 C# 中,一些 identifiers 在代码上下文中具有特殊含义,例如 get 和 set 被称为 contextual keywords。

下表列出了 C# 中的保留 keywords 和 contextual keywords −

保留 Keywords
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
foreach goto if implicit in in (generic modifier) int
interface internal is lock long namespace new
null object operator out out (generic modifier) override params
private protected public readonly ref return sbyte
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile while
Contextual Keywords
add alias ascending descending dynamic from get
global group into join let orderby partial (type)
partial
(method)
remove select set

C# 控制流语句

条件语句

ifelseswitch 这样的控制语句决定了程序的流程。

在下面的示例中,我们使用 if-else 语句检查投票资格:

int age = 18;
if (age >= 18)
{
    Console.WriteLine("You are eligible to vote."); // 输出:You are eligible to vote.
}
else
{
    Console.WriteLine("You are not eligible to vote.");
}

循环结构

循环有助于多次执行代码。

For Loop

在下面的示例中,我们使用 for loop 打印迭代次数:

for (int i = 1; i 

当上述代码编译并执行时,会产生以下结果 −

Iteration: 1
Iteration: 2
Iteration: 3

While Loop

在下面的示例中,我们使用 while loop 打印计数值:

int count = 1;
while (count <= 3)
{
    Console.WriteLine("Count: " + count);
    count++;
}

当上述代码编译并执行时,会产生以下结果 −

Count: 1
Count: 2
Count: 3

C# 数据输入与输出

向控制台打印输出

您可以使用 Console.WriteLine() 在控制台显示文本。

在下面的示例中,我们打印一条消息:

Console.WriteLine("Welcome to C#"); // 输出:Welcome to C#

获取用户输入

您可以使用 Console.ReadLine() 从用户获取输入。

在下面的示例中,我们询问用户姓名并显示它:

Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");

当上述代码编译并执行时,会产生以下结果(取决于用户输入)−

Enter your name: Alice
Hello, Alice!

C# 中的错误处理

使用 try-catch 块来优雅地处理错误。

在下面的示例中,我们处理无效转换错误:

try
{
    int num = Convert.ToInt32("ABC"); // 错误:无法将字符串转换为 int
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
}
    

当上述代码编译并执行时,会产生以下结果 −

Error: Input string was not in a correct format.

C# 语法最佳实践

编写 C# 代码时,应遵循以下最佳实践,以使代码清晰、可读且易于维护:

  • 使用有意义的变量名(例如 customerName 而非 cn),使代码易于理解。
  • 遵循 C# 命名规则(变量使用 camelCase,class 使用 PascalCase),保持代码一致性。
  • 通过适当的缩进和必要的注释,使代码易读。
  • 避免硬编码值;相反,使用 constants 或配置文件以提高灵活性。
  • 始终使用 try-catch 块正确处理错误,以防止崩溃。