在本节中,我们将创建并运行我们的第一个C#程序。我们将从最简单的"Hello World"开始,然后逐步添加更多功能,以展示C#的基本特性。
创建新项目:
配置项目:
编写代码:
// Program.cs
// 魔法开始的地方!Main方法是程序入口
public static void Main(string[] args)
{
// Console是系统自带的控制台工具箱
Console.WriteLine("Hello, World!");
// 等待用户输入名字
Console.Write("请输入您的名字:");
// ?表示name可以是null,避免黄牌警告
string? name = Console.ReadLine();
// $符号开启字符串插值模式,比拼接更优雅
Console.WriteLine($"你好,{name}!欢迎来到C#世界!");
// 等待用户按键,防止程序立即退出
Console.WriteLine("\n按任意键退出...");
Console.ReadKey();
}
运行程序:
创建项目文件夹:
mkdir HelloWorld
cd HelloWorld
创建新项目:
dotnet new console
打开VS Code:
code .
编写代码:
// Program.cs
// 魔法开始的地方!Main方法是程序入口
public static void Main(string[] args)
{
// Console是系统自带的控制台工具箱
Console.WriteLine("Hello, World!");
// 等待用户输入名字
Console.Write("请输入您的名字:");
// ?表示name可以是null,避免黄牌警告
string? name = Console.ReadLine();
// $符号开启字符串插值模式,比拼接更优雅
Console.WriteLine($"你好,{name}!欢迎来到C#世界!");
// 等待用户按键,防止程序立即退出
Console.WriteLine("\n按任意键退出...");
Console.ReadKey();
}
运行程序:
dotnet run
让我们通过一些有趣的练习来加深对C#的理解:
将欢迎语改成你家乡的方言:
// 根据用户输入选择方言
Console.Write("请选择方言(1:粤语,2:东北话,3:四川话):");
string? choice = Console.ReadLine();
string greeting = choice switch
{
"1" => "你好啊,{0}!欢迎来到C#世界!",
"2" => "老铁,{0}!欢迎来到C#世界!",
"3" => "巴适得很,{0}!欢迎来到C#世界!",
_ => "你好,{0}!欢迎来到C#世界!"
};
Console.WriteLine(string.Format(greeting, name));
添加倒计时功能:
// 倒计时功能
Console.WriteLine("\n程序将在5秒后退出...");
for (int i = 5; i > 0; i--)
{
Console.WriteLine($"倒计时:{i}秒");
Thread.Sleep(1000); // 暂停1秒
}
Console.WriteLine("再见!");
当用户输入特定内容时显示彩蛋:
// 检查是否是管理员
if (name?.ToLower() == "admin")
{
Console.WriteLine("\n 恭喜你发现了隐藏彩蛋!");
Console.WriteLine("正在加载彩蛋内容...");
Thread.Sleep(1000);
// 显示ASCII艺术
Console.WriteLine(@"
╔══════════════════════════════════════╗
║ 欢迎回来,管理员! ║
║ ║
║ ██████╗ ██████╗ ███████╗██╗███╗ ║
║ ██╔════╝██╔═══██╗██╔════╝██║████║ ║
║ ██║ ██║ ██║█████╗ ██║██╔██║ ║
║ ██║ ██║ ██║██╔══╝ ██║██║██║ ║
║ ╚██████╗╚██████╔╝███████╗██║██║██║ ║
║ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚═╝╚═╝ ║
║ ║
╚══════════════════════════════════════╝
");
}
让我们详细解释C#程序的基本结构:
// 1. 命名空间声明
namespace MyFirstProgram;
// 2. 类声明
public class Program
{
// 3. 主方法
public static void Main(string[] args)
{
// 4. 程序语句
Console.WriteLine("Hello, World!");
// 5. 变量声明和使用
string message = "Welcome to C#!";
Console.WriteLine(message);
// 6. 用户输入
Console.Write("请输入一个数字:");
string? input = Console.ReadLine();
// 7. 类型转换和计算
if (int.TryParse(input, out int number))
{
int result = number * 2;
Console.WriteLine($"您输入的数字乘以2等于:{result}");
}
else
{
Console.WriteLine("输入无效,请输入一个有效的数字。");
}
}
}
命名空间(Namespace):
using
关键字导入其他命名空间类(Class):
public
关键字使类可被其他程序集访问方法(Method):
Main
方法是程序的入口点static
关键字表示方法属于类而不是实例变量和数据类型:
// 基本数据类型
int number = 42; // 整数
double pi = 3.14159; // 浮点数
bool isTrue = true; // 布尔值
char letter = 'A'; // 字符
string text = "Hello"; // 字符串
// 可空类型
int? nullableNumber = null; // 可空整数
string? nullableText = null; // 可空字符串
控制流:
// if语句
if (condition)
{
// 代码块
}
else if (anotherCondition)
{
// 代码块
}
else
{
// 代码块
}
// for循环
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"计数:{i}");
}
// while循环
while (condition)
{
// 代码块
}
设置断点:
条件断点:
单步执行:
监视窗口:
局部变量窗口:
即时窗口:
语法错误:
// 错误示例
Console.WriteLine("Hello World" // 缺少分号
// 正确示例
Console.WriteLine("Hello World"); // 添加分号
类型错误:
// 错误示例
string text = 42; // 不能将int赋值给string
// 正确示例
string text = "42"; // 使用字符串
// 或
string text = 42.ToString(); // 转换为字符串
未定义变量:
// 错误示例
Console.WriteLine(undefinedVariable); // 变量未定义
// 正确示例
string definedVariable = "Hello";
Console.WriteLine(definedVariable);
命名规范:
// 类名使用PascalCase
public class UserAccount
// 方法名使用PascalCase
public void CalculateTotal()
// 变量名使用camelCase
string userName;
// 常量使用UPPER_CASE
const int MAX_RETRY_COUNT = 3;
代码组织:
// 使用区域组织代码
#region Properties
public string Name { get; set; }
public int Age { get; set; }
#endregion
#region Methods
public void DoSomething()
{
// 方法实现
}
#endregion
注释规范:
///
/// 计算两个数字的和
///
/// 第一个数字
/// 第二个数字
/// 两个数字的和
public int Add(int a, int b)
{
return a + b;
}
基础练习:
进阶练习:
挑战练习:
在本节中,我们:
这些基础知识为我们后续学习更复杂的C#概念打下了基础。在下一章中,我们将深入学习C#的数据类型和变量。