C# 环境设置C# 基本语法
C# - 程序结构更新于 2025/6/9 9:37:17
在学习 C# 编程语言的基本构建块之前,让我们先了解一下 C# 程序的最小结构,以便在接下来的章节中作为参考。
C# 程序的基本结构
C# 程序遵循简单的结构,包含必要的组件。基本程序如下所示:
创建 Hello World 程序
让我们看一段打印"Hello World"的简单代码 -
using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { /* 我的第一个 C# 程序 */ Console.WriteLine("Hello World"); Console.ReadKey(); } } }此代码编译并执行后,将产生以下结果 -
Hello World
让我们来看看给定程序的各个部分 -
C# 程序的关键组件1. 命名空间声明
命名空间通过将相关类分组在一起来帮助组织大型程序。
namespace MyApplication { class Program { static void Main() { Console.WriteLine("Hello from MyApplication!"); } } }当编译并执行上述代码时,它会产生以下结果 -
Hello from MyApplication!
2. 使用指令 (using)
using 语句导入命名空间,允许访问内置类和方法。
using System; // 启用 Console.WriteLine() 函数 class Example { static void Main() { Console.WriteLine("Using directive example."); } }当编译并执行上述代码时,它会产生以下结果 -
Using directive example.
3. 类声明
C# 是一种面向对象的语言,每个程序都必须至少有一个类。
class Car { string model = "Tesla"; static void Main() { Car myCar = new Car(); Console.WriteLine("Car Model: " + myCar.model); } }当编译并执行上述代码时,它会产生以下结果 -
Car Model: Tesla
4. Main() 方法
Main() 方法是每个 C# 程序的入口点。
using System; class Start { static void Main() { Console.WriteLine("This is the main entry point of the program."); } }当编译并执行上述代码时,它会产生以下结果 -
This is the main entry point of the program.
5. 语句和表达式
Main() 方法中的每条指令都是一条语句。
class StatementsExample { static void Main() { int a = 5, b = 10; int sum = a + b; Console.WriteLine("Sum: " + sum); } }当编译并执行上述代码时,它会产生以下结果 -
Sum: 15
6. 访问修饰符
访问修饰符定义类和方法的可见性。
类示例 { private int secretNumber = 42; // Private:仅在此类内可访问 public void Display() { Console.WriteLine("Access Modifier Example: " + secretNumber); } } class Program { static void Main() { Example obj = new Example(); obj.Display(); } }当编译并执行上述代码时,它会产生以下结果 -
Access Modifier Example: 42
组织 C# 程序
结构良好的程序更易于阅读、运行更流畅、维护更简单。
示例:结构良好的 C# 程序
以下是一个真实示例,演示了一个包含多个组件的结构化 C# 程序:
using System; namespace School { class Student { public string Name; public int Age; public void DisplayStudentInfo() { Console.WriteLine("Student Name: " + Name); Console.WriteLine("Student Age: " + Age); } } class Program { static void Main() { Student student1 = new Student(); student1.Name = "Alice"; student1.Age = 14; student1.DisplayStudentInfo(); } } }当编译并执行上述代码时,它会产生以下结果 -
Student Name: Alice Student Age: 14
需要注意以下几点 -
编译和执行程序
如果您使用 Visual Studio.Net 编译和执行 C# 程序,请执行以下步骤 -
使用命令行编译和执行程序
您可以使用命令行而不是 Visual Studio IDE 来编译 C# 程序 -
C# 环境设置C# 基本语法