C# - 基本语法
C# 是一种面向对象的编程语言。在面向对象编程方法论中,程序由各种对象组成,这些对象通过操作相互交互。对象可能执行的操作称为方法。同类对象被称为具有相同的类型,或者说属于同一个类。
C# 程序的基本结构
每个 C# 程序都有一个基本结构。以下是一个简单的示例:
示例
例如,我们考虑一个 Rectangle 对象。它具有长度和宽度等属性。根据设计,它可能需要一些方法来接受这些属性的值、计算面积以及显示详细信息。
让我们看一下 Rectangle 类的实现,并讨论 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); // 输出:10
3. 花括号 {} 定义代码块
花括号将函数、循环和条件语句中的语句组合在一起。
以下示例中,我们在 if 语句中使用了花括号:
int x = 7; if (x > 5) { Console.WriteLine("x 大于 5"); // 输出:x 大于 5 }
4. 缩进和空格
C# 会忽略多余的空格和换行符,但适当的缩进可以使代码更具可读性。
在以下示例中,我们使用缩进来提高可读性:
int x = 5; int y = 10; Console.WriteLine(x + y); // 输出:15
using 关键字
任何 C# 程序中的第一个语句都是
using System;
using 关键字用于在程序中包含命名空间。一个程序可以包含多个 using 语句。
class 关键字
class 关键字用于声明类。
C# 中的注释
注释用于解释代码。编译器会忽略注释条目。C# 程序中的多行注释以 /* 开头,以字符 */ 结尾,如下所示 -
/* This program demonstrates The basic syntax of C# programming Language */
单行注释用"//"符号表示。例如:
}//end class Rectangle
成员变量
变量是类的属性或数据成员,用于存储数据。在上面的程序中,Rectangle类有两个成员变量,分别为length和width。
成员函数
函数是执行特定任务的语句集合。类的成员函数在类内部声明。我们的示例类 Rectangle 包含三个成员函数:AcceptDetails、GetArea 和 Display。
实例化类
在上面的程序中,类 ExecuteRectangle 包含 Main() 方法,并实例化了 Rectangle 类。
标识符
标识符是用于标识类、变量、函数或任何其他用户定义项的名称。C# 中类命名的基本规则如下:
名称必须以字母开头,后跟字母、数字(0 - 9)或下划线序列。标识符中的第一个字符不能是数字。
它不能包含任何嵌入的空格或符号,例如?-+!@#%^&*()[]{}.; : " ' / 和 \。但是,可以使用下划线 ( _ )。
它不应该是 C# 关键字。
C# 关键字
关键字是 C# 编译器预定义的保留字。这些关键字不能用作标识符。但是,如果您想使用这些关键字作为标识符,可以在关键字前加上 @ 字符。
在 C# 中,某些标识符在代码上下文中具有特殊含义,例如 get 和 set,它们被称为上下文关键字。
下表列出了 C# 中的保留关键字和上下文关键字 -
保留关键字 | ||||||
---|---|---|---|---|---|---|
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# 控制流语句
条件语句
诸如 if
、else
和 switch
之类的控制语句决定了程序的流程。
在以下示例中,我们使用 if-else 语句检查投票资格:
int age = 18; if (age >= 18) { Console.WriteLine("You are eligible to vote."); } else { Console.WriteLine("You are not eligible to vote."); }
循环结构
循环有助于多次执行代码。
For 循环
在下面的示例中,我们使用 for
循环来打印迭代:
for (int i = 1; i当编译并执行上述代码时,它会产生以下结果 -
Iteration: 1 Iteration: 2 Iteration: 3While 循环
在下面的示例中,我们使用
while
循环来打印计数值:int count = 1; while (count <= 3) { Console.WriteLine("Count: " + count); count++; }当编译并执行上述代码时,它会产生以下结果 -
Count: 1 Count: 2 Count: 3C# 数据输入与输出
将输出打印到控制台
您可以使用
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"); // Error: Cannot convert string to int } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); }当编译并执行上述代码时,它会产生以下结果 -
Error: Input string was not in a correct format.C# 语法最佳实践
以下是编写 C# 代码时应遵循的最佳实践,以确保代码清晰、易读且易于维护:
- 使用有意义的变量名(例如,使用
customerName
而不是cn
),使代码易于理解。 - 遵循 C# 命名规则(变量使用
camelCase
,类使用PascalCase
),以保持代码的一致性。 - 使用适当的缩进并在需要时添加注释,以保持代码的可读性。
- 避免对值进行硬编码;相反,请使用常量或配置文件来提高灵活性。
- 始终使用
try-catch
块正确处理错误,以防止崩溃。