第一个C#程序 #
一、Hello World #
1.1 最简单的C#程序 #
从C# 9.0开始,可以使用顶级语句(Top-level statements):
csharp
Console.WriteLine("Hello, World!");
这就是一个完整的C#程序!只需要一行代码。
1.2 传统程序结构 #
在C# 9.0之前,程序需要完整的类结构:
csharp
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
二、程序结构解析 #
2.1 顶级语句程序 #
csharp
using System;
Console.WriteLine("Hello, World!");
Console.WriteLine("欢迎使用C#!");
特点:
- 无需定义类和Main方法
- 代码简洁直观
- 适合简单程序和脚本
2.2 传统程序结构 #
csharp
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
各部分说明:
| 部分 | 说明 |
|---|---|
using System; |
导入System命名空间 |
namespace |
命名空间,组织代码 |
class Program |
类定义 |
static void Main |
程序入口点 |
Console.WriteLine |
控制台输出 |
2.3 命名空间 #
命名空间用于组织代码,避免命名冲突:
csharp
namespace Company.Project.Module
{
class MyClass
{
}
}
文件范围命名空间(C# 10+):
csharp
namespace Company.Project.Module;
class MyClass
{
}
2.4 Main方法 #
Main方法是程序的入口点,有多种形式:
csharp
static void Main() { }
static void Main(string[] args) { }
static int Main() { return 0; }
static int Main(string[] args) { return 0; }
static async Task Main() { }
static async Task<int> Main() { return 0; }
static async Task Main(string[] args) { }
static async Task<int> Main(string[] args) { return 0; }
三、控制台输入输出 #
3.1 输出方法 #
Console.Write
不换行输出:
csharp
Console.Write("Hello");
Console.Write(" ");
Console.Write("World");
输出:Hello World
Console.WriteLine
换行输出:
csharp
Console.WriteLine("第一行");
Console.WriteLine("第二行");
输出:
text
第一行
第二行
3.2 格式化输出 #
使用占位符
csharp
string name = "张三";
int age = 25;
Console.WriteLine("姓名:{0},年龄:{1}", name, age);
使用字符串插值(推荐)
csharp
string name = "张三";
int age = 25;
Console.WriteLine($"姓名:{name},年龄:{age}");
格式化数字
csharp
double price = 123.456;
Console.WriteLine($"价格:{price:F2}");
Console.WriteLine($"价格:{price:C}");
输出:
text
价格:123.46
价格:¥123.46
3.3 读取输入 #
Console.ReadLine
读取一行文本:
csharp
Console.Write("请输入您的名字:");
string name = Console.ReadLine();
Console.WriteLine($"您好,{name}!");
Console.Read
读取单个字符的ASCII码:
csharp
Console.Write("请输入一个字符:");
int ch = Console.Read();
Console.WriteLine($"您输入的字符ASCII码是:{ch}");
Console.ReadKey
读取单个按键:
csharp
Console.WriteLine("按任意键继续...");
Console.ReadKey();
3.4 完整交互示例 #
csharp
Console.WriteLine("=== 用户信息录入 ===");
Console.Write("请输入姓名:");
string name = Console.ReadLine();
Console.Write("请输入年龄:");
int age = int.Parse(Console.ReadLine());
Console.Write("请输入城市:");
string city = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("=== 用户信息 ===");
Console.WriteLine($"姓名:{name}");
Console.WriteLine($"年龄:{age}");
Console.WriteLine($"城市:{city}");
四、编译与运行 #
4.1 使用dotnet CLI #
bash
dotnet new console -n HelloWorld
cd HelloWorld
dotnet run
4.2 手动编译 #
bash
dotnet build
dotnet ./bin/Debug/net8.0/HelloWorld.dll
4.3 发布应用程序 #
发布为可执行文件
bash
dotnet publish -c Release -r win-x64 --self-contained
dotnet publish -c Release -r linux-x64 --self-contained
dotnet publish -c Release -r osx-x64 --self-contained
发布为单文件
bash
dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true
4.4 编译过程 #
text
源代码(.cs)
↓
C#编译器
↓
程序集(.dll/.exe)
↓
CLR运行时
↓
机器码执行
五、注释 #
5.1 单行注释 #
csharp
int x = 10;
5.2 多行注释 #
csharp
int a = 1;
int b = 2;
int c = a + b;
5.3 文档注释 #
csharp
/// <summary>
/// 计算两个数的和
/// </summary>
/// <param name="a">第一个数</param>
/// <param name="b">第二个数</param>
/// <returns>两数之和</returns>
public static int Add(int a, int b)
{
return a + b;
}
六、代码规范 #
6.1 命名规范 #
| 类型 | 规范 | 示例 |
|---|---|---|
| 类名 | PascalCase | public class MyClass |
| 方法名 | PascalCase | public void DoWork() |
| 属性 | PascalCase | public string Name { get; set; } |
| 参数 | camelCase | void Method(string userName) |
| 局部变量 | camelCase | int totalCount = 0; |
| 私有字段 | _camelCase | private int _count; |
| 常量 | PascalCase或UPPER_CASE | public const int MaxSize = 100; |
6.2 代码格式 #
缩进
使用4个空格缩进:
csharp
if (condition)
{
DoSomething();
}
大括号
使用Allman风格或K&R风格:
csharp
if (condition) {
DoSomething();
}
if (condition)
{
DoSomething();
}
一行一条语句
csharp
int a = 1;
int b = 2;
6.3 using语句 #
传统方式
csharp
using System;
using System.Collections.Generic;
using System.Linq;
全局using(C# 10+)
csharp
global using System;
global using System.Collections.Generic;
隐式using
在项目文件中启用:
xml
<ImplicitUsings>enable</ImplicitUsings>
七、实战练习 #
7.1 练习一:个人信息 #
创建一个程序,输出您的个人信息:
csharp
Console.WriteLine("=== 个人信息 ===");
Console.WriteLine("姓名:张三");
Console.WriteLine("年龄:25");
Console.WriteLine("职业:软件工程师");
Console.WriteLine("爱好:编程、阅读、运动");
7.2 练习二:简单计算器 #
csharp
Console.WriteLine("=== 简单计算器 ===");
Console.Write("请输入第一个数:");
double num1 = double.Parse(Console.ReadLine());
Console.Write("请输入第二个数:");
double num2 = double.Parse(Console.ReadLine());
Console.WriteLine($"加法:{num1} + {num2} = {num1 + num2}");
Console.WriteLine($"减法:{num1} - {num2} = {num1 - num2}");
Console.WriteLine($"乘法:{num1} × {num2} = {num1 * num2}");
Console.WriteLine($"除法:{num1} ÷ {num2} = {num1 / num2}");
7.3 练习三:温度转换 #
csharp
Console.WriteLine("=== 摄氏度转华氏度 ===");
Console.Write("请输入摄氏度:");
double celsius = double.Parse(Console.ReadLine());
double fahrenheit = celsius * 9 / 5 + 32;
Console.WriteLine($"{celsius}°C = {fahrenheit}°F");
八、常见错误 #
8.1 语法错误 #
csharp
Console.WriteLine("Hello"
错误:缺少右括号和分号
8.2 运行时错误 #
csharp
int number = int.Parse("abc");
错误:字符串无法转换为整数
8.3 命名错误 #
csharp
console.WriteLine("Hello");
错误:C#区分大小写,应为Console
九、总结 #
第一个C#程序要点:
| 要点 | 说明 |
|---|---|
| 入口点 | Main方法或顶级语句 |
| 输出 | Console.WriteLine |
| 输入 | Console.ReadLine |
| 编译 | dotnet build |
| 运行 | dotnet run |
| 注释 | //、/* */、/// |
下一步,让我们深入学习C#的基础语法!
最后更新:2026-03-26