一、什么是 C#?
C#(读作 "C Sharp")是微软开发的一种面向对象 、类型安全的编程语言,运行在 .NET 框架之上。它结合了 C/C++ 的强大功能和 Java 的简洁性,广泛应用于:
- 桌面应用开发(WinForms、WPF)
- Web 应用开发(ASP.NET)
- 游戏开发(Unity 引擎)
- 移动开发(Xamarin)
- 云服务和微服务
二、开发环境搭建
安装 .NET SDK
- 访问 https://dotnet.microsoft.com/download
- 下载并安装最新版本的 .NET SDK
- 打开命令行(CMD 或 PowerShell),输入以下命令验证安装:
bash
dotnet --version
如果显示版本号,说明安装成功。
选择 IDE
| IDE | 适用场景 | 价格 |
|---|---|---|
| Visual Studio | 企业级开发,功能最全 | 社区版免费 |
| Visual Studio Code | 轻量级开发,跨平台 | 免费 |
| JetBrains Rider | 专业 .NET 开发 | 付费 |
三、你的第一个 C# 程序
创建项目
打开终端,执行以下命令:
bash
dotnet new console -n HelloWorld
cd HelloWorld
编写代码
打开 Program.cs 文件,写入以下代码:
csharp
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("欢迎学习 C# 编程!");
}
}
}
运行程序
bash
dotnet run
输出结果:
Hello, World!
欢迎学习 C# 编程!
四、C# 基础语法
1. 变量与数据类型
C# 是强类型语言,声明变量时必须指定类型。
csharp
// 值类型
int age = 25; // 整数
double price = 19.99; // 双精度浮点数
float pi = 3.14f; // 单精度浮点数
decimal salary = 5000.00m; // 高精度十进制数
char grade = 'A'; // 字符
bool isActive = true; // 布尔值
// 引用类型
string name = "张三"; // 字符串
object obj = "任何类型"; // 所有类型的基类
2. 类型推断 - var 关键字
csharp
var message = "Hello"; // 编译器自动推断为 string
var count = 100; // 编译器自动推断为 int
3. 常量
csharp
const double PI = 3.14159;
const string AppName = "我的应用";
4. 字符串操作
csharp
string firstName = "张";
string lastName = "三";
// 字符串拼接
string fullName = firstName + lastName;
// 字符串插值(推荐)
string greeting = $"你好,{fullName}!";
// 字符串方法
string text = " Hello World ";
Console.WriteLine(text.Length); // 输出长度
Console.WriteLine(text.Trim()); // 去除首尾空格
Console.WriteLine(text.ToUpper()); // 转大写
Console.WriteLine(text.Replace("World", "C#")); // 替换
五、控制流语句
if-else 条件判断
csharp
int score = 85;
if (score >= 90)
{
Console.WriteLine("优秀");
}
else if (score >= 80)
{
Console.WriteLine("良好");
}
else if (score >= 60)
{
Console.WriteLine("及格");
}
else
{
Console.WriteLine("不及格");
}
switch 语句
csharp
string day = "周一";
switch (day)
{
case "周一":
Console.WriteLine("新的一周开始");
break;
case "周五":
Console.WriteLine("即将周末");
break;
case "周六":
case "周日":
Console.WriteLine("周末愉快");
break;
default:
Console.WriteLine("工作日");
break;
}
循环语句
csharp
// for 循环
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"第 {i + 1} 次循环");
}
// foreach 循环
string[] fruits = { "苹果", "香蕉", "橙子" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// while 循环
int count = 0;
while (count < 3)
{
Console.WriteLine($"计数: {count}");
count++;
}
六、数组与集合
数组
csharp
// 声明并初始化数组
int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = new string[3] { "Tom", "Jerry", "Spike" };
// 访问数组元素
Console.WriteLine(numbers[0]); // 输出 1
Console.WriteLine(names[1]); // 输出 Jerry
// 数组长度
Console.WriteLine($"数组长度: {numbers.Length}");
List 集合
csharp
using System.Collections.Generic;
// 创建 List
List<string> cities = new List<string>();
cities.Add("北京");
cities.Add("上海");
cities.Add("广州");
// 遍历 List
foreach (string city in cities)
{
Console.WriteLine(city);
}
// List 常用方法
Console.WriteLine(cities.Count); // 元素个数
cities.Remove("上海"); // 删除元素
cities.Contains("北京"); // 是否包含
七、方法(函数)
csharp
// 定义方法
static int Add(int a, int b)
{
return a + b;
}
// 带默认参数的方法
static void Greet(string name, string greeting = "你好")
{
Console.WriteLine($"{greeting},{name}!");
}
// 调用方法
int sum = Add(10, 20);
Console.WriteLine($"10 + 20 = {sum}");
Greet("小明"); // 输出:你好,小明!
Greet("小明", "早上好"); // 输出:早上好,小明!
八、面向对象编程基础
类与对象
csharp
// 定义一个类
public class Person
{
// 属性
public string Name { get; set; }
public int Age { get; set; }
// 构造函数
public Person(string name, int age)
{
Name = name;
Age = age;
}
// 方法
public void Introduce()
{
Console.WriteLine($"我叫 {Name},今年 {Age} 岁。");
}
}
// 创建对象并使用
Person person = new Person("小李", 25);
person.Introduce();
继承
csharp
// 基类
public class Animal
{
public string Name { get; set; }
public virtual void MakeSound()
{
Console.WriteLine("动物发出声音");
}
}
// 派生类
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("汪汪!");
}
}
// 使用继承
Dog dog = new Dog();
dog.Name = "旺财";
dog.MakeSound(); // 输出:汪汪!
九、异常处理
csharp
try
{
int[] arr = { 1, 2, 10 };
int result = arr[5]; // 会引发异常
}
catch (IndexOutOfBoundsException ex)
{
Console.WriteLine($"数组越界:{ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"发生错误:{ex.Message}");
}
finally
{
Console.WriteLine("无论是否出错都会执行");
}
十、实战小练习:简易计算器
csharp
using System;
class Calculator
{
static void Main(string[] args)
{
Console.WriteLine("=== 简易计算器 ===");
Console.Write("请输入第一个数字:");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("请输入运算符(+、-、*、/):");
string op = Console.ReadLine();
Console.Write("请输入第二个数字:");
double num2 = Convert.ToDouble(Console.ReadLine());
double result = 0;
switch (op)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0)
{
result = num1 / num2;
}
else
{
Console.WriteLine("除数不能为 0");
return;
}
break;
default:
Console.WriteLine("无效的运算符");
return;
}
Console.WriteLine($"结果:{num1} {op} {num2} = {result}");
}
}
总结
本文介绍了 C# 的核心基础知识:
| 知识点 | 说明 |
|---|---|
| 变量和数据类型 | 掌握值类型和引用类型 |
| 控制流 | if、switch、循环 |
| 数组和集合 | List、数组的使用 |
| 面向对象 | 类、继承、多态 |
| 异常处理 | try-catch 机制 |
C# 是一门功能强大且不断进化的语言,学好基础后可以继续深入学习 LINQ、LINQ、异步编程、LINQ、委托与事件、LINQ、ASP.NET Core 等内容。
学习建议: 多写代码、多实践,把上面的示例都亲手敲一遍,遇到问题善用搜索引擎和官方文档。
祝你编程愉快!🚀----
本文由 OpenCowork 全自动生成并发布到博客园。OpenCowork 是一个开源的 AI 协作工具,让 AI 真正「会干活」。