# C# 基础语法完全指南

C# 基础语法完全指南

一、C# 编程基础

1. 第一个C#程序

csharp 复制代码
using System;  // 引入命名空间

namespace HelloWorld  // 命名空间声明
{
    class Program     // 类声明
    {
        static void Main(string[] args)  // 主方法(程序入口)
        {
            Console.WriteLine("Hello, World!");  // 输出语句
            Console.ReadLine();  // 等待用户输入
        }
    }
}

2. 变量和数据类型

基本数据类型
csharp 复制代码
// 数值类型
int age = 25;                     // 整数,4字节
long bigNumber = 10000000000L;    // 长整数,8字节
float price = 19.99f;             // 单精度浮点数
double distance = 123.45;         // 双精度浮点数
decimal money = 999.99m;          // 高精度小数(财务计算)

// 字符和字符串
char grade = 'A';                 // 单个字符
string name = "张三";             // 字符串
bool isStudent = true;            // 布尔值

// 使用示例
int score = 95;
string studentName = "李四";
bool isPassed = score >= 60;
Console.WriteLine($"{studentName}的分数是{score},{(isPassed ? "及格" : "不及格")}");
声明和初始化
csharp 复制代码
// 声明变量
int count;           // 声明
count = 10;          // 赋值

// 声明并初始化
string message = "Hello";
var number = 42;     // 使用var,编译器自动推断类型

// 常量
const double PI = 3.14159;
const string APP_NAME = "我的应用";

// 多个变量声明
int x = 1, y = 2, z = 3;

3. 运算符

算术运算符
csharp 复制代码
int a = 10, b = 3;

int sum = a + b;      // 13,加法
int difference = a - b;  // 7,减法
int product = a * b;  // 30,乘法
int quotient = a / b; // 3,整数除法
int remainder = a % b; // 1,取余
float realQuotient = (float)a / b; // 3.333...,浮点除法

// 自增自减
int i = 5;
i++;    // i = 6,后置自增
++i;    // i = 7,前置自增
i--;    // i = 6,后置自减
比较运算符
csharp 复制代码
int x = 10, y = 20;

bool isEqual = (x == y);        // false,等于
bool notEqual = (x != y);       // true,不等于
bool greater = (x > y);         // false,大于
bool less = (x < y);            // true,小于
bool greaterOrEqual = (x >= y); // false,大于等于
bool lessOrEqual = (x <= y);    // true,小于等于
逻辑运算符
csharp 复制代码
bool a = true, b = false;

bool andResult = a && b;    // false,逻辑与
bool orResult = a || b;     // true,逻辑或
bool notResult = !a;        // false,逻辑非

// 条件运算符
int score = 85;
string result = (score >= 60) ? "及格" : "不及格";
Console.WriteLine(result);  // 输出:及格

4. 控制流程

条件语句
csharp 复制代码
// if-else
int score = 75;

if (score >= 90)
{
    Console.WriteLine("优秀");
}
else if (score >= 80)
{
    Console.WriteLine("良好");
}
else if (score >= 60)
{
    Console.WriteLine("及格");
}
else
{
    Console.WriteLine("不及格");
}

// switch语句
string day = "Monday";

switch (day)
{
    case "Monday":
        Console.WriteLine("星期一");
        break;
    case "Tuesday":
        Console.WriteLine("星期二");
        break;
    case "Wednesday":
        Console.WriteLine("星期三");
        break;
    default:
        Console.WriteLine("其他日子");
        break;
}

// 模式匹配(C# 7.0+)
object obj = "Hello";
if (obj is string str)
{
    Console.WriteLine($"字符串长度:{str.Length}");
}
循环语句
csharp 复制代码
// for循环
Console.WriteLine("for循环示例:");
for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"i = {i}");
}

// while循环
Console.WriteLine("\nwhile循环示例:");
int count = 0;
while (count < 3)
{
    Console.WriteLine($"count = {count}");
    count++;
}

// do-while循环
Console.WriteLine("\ndo-while循环示例:");
int num = 0;
do
{
    Console.WriteLine($"num = {num}");
    num++;
} while (num < 3);

// foreach循环(遍历集合)
Console.WriteLine("\nforeach循环示例:");
string[] fruits = { "苹果", "香蕉", "橙子" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

// break和continue
Console.WriteLine("\nbreak和continue示例:");
for (int i = 0; i < 10; i++)
{
    if (i == 5)
        break;      // 跳出循环
    
    if (i % 2 == 0)
        continue;   // 跳过本次循环
    
    Console.WriteLine(i);  // 输出:1, 3
}

二、面向对象编程基础

1. 类和方法

定义类
csharp 复制代码
// 定义一个学生类
public class Student
{
    // 字段(私有)
    private string name;
    private int age;
    
    // 属性(公有)
    public string Name
    {
        get { return name; }
        set 
        { 
            if (!string.IsNullOrWhiteSpace(value))
                name = value; 
        }
    }
    
    public int Age
    {
        get { return age; }
        set 
        { 
            if (value > 0 && value < 150)
                age = value; 
        }
    }
    
    // 自动属性(简洁写法)
    public string StudentId { get; set; }
    
    // 构造函数
    public Student(string name, int age)
    {
        Name = name;
        Age = age;
        StudentId = GenerateStudentId();
    }
    
    // 默认构造函数
    public Student() : this("未知", 18)
    {
    }
    
    // 方法
    public void Introduce()
    {
        Console.WriteLine($"我叫{Name},今年{Age}岁,学号是{StudentId}");
    }
    
    // 私有方法
    private string GenerateStudentId()
    {
        return "S" + DateTime.Now.ToString("yyyyMMddHHmmss");
    }
    
    // 静态方法
    public static void ShowSchoolInfo()
    {
        Console.WriteLine("欢迎来到XX学校");
    }
}
使用类
csharp 复制代码
// 创建对象
Student student1 = new Student("张三", 20);
student1.Introduce();  // 我叫张三,今年20岁...

Student student2 = new Student();  // 使用默认构造函数
student2.Name = "李四";
student2.Age = 19;

// 调用静态方法
Student.ShowSchoolInfo();

2. 继承和多态

csharp 复制代码
// 基类
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public virtual void Introduce()  // 虚方法
    {
        Console.WriteLine($"我是{Name},{Age}岁");
    }
}

// 派生类
public class Teacher : Person
{
    public string Subject { get; set; }
    
    // 重写方法
    public override void Introduce()
    {
        base.Introduce();  // 调用基类方法
        Console.WriteLine($"我教{Subject}科目");
    }
    
    // 新方法
    public void Teach()
    {
        Console.WriteLine($"{Name}老师正在教{Subject}");
    }
}

// 使用
Person person = new Person { Name = "王五", Age = 30 };
person.Introduce();  // 我是王五,30岁

Teacher teacher = new Teacher 
{ 
    Name = "张老师", 
    Age = 35, 
    Subject = "数学" 
};
teacher.Introduce();  // 我是张老师,35岁 \n 我教数学科目
teacher.Teach();      // 张老师正在教数学

// 多态示例
Person p = new Teacher { Name = "李老师", Subject = "英语" };
p.Introduce();  // 调用Teacher的Introduce方法

3. 接口

csharp 复制代码
// 定义接口
public interface IAnimal
{
    void Eat();      // 接口方法
    void Sleep();    // 接口方法
    string Name { get; }  // 接口属性
}

// 实现接口
public class Dog : IAnimal
{
    public string Name { get; set; }
    
    public void Eat()
    {
        Console.WriteLine($"{Name}在吃狗粮");
    }
    
    public void Sleep()
    {
        Console.WriteLine($"{Name}在睡觉");
    }
    
    public void Bark()  // 自己的方法
    {
        Console.WriteLine($"{Name}在汪汪叫");
    }
}

// 使用接口
IAnimal animal = new Dog { Name = "小黑" };
animal.Eat();    // 小黑在吃狗粮
animal.Sleep();  // 小黑在睡觉

// 接口引用只能调用接口方法
// animal.Bark();  // 错误!不能调用Dog特有的方法

三、集合和数组

1. 数组

csharp 复制代码
// 一维数组
int[] numbers = new int[5];  // 声明长度为5的数组
numbers[0] = 10;             // 赋值
numbers[1] = 20;

int[] scores = { 85, 90, 78, 95, 88 };  // 声明并初始化

// 遍历数组
for (int i = 0; i < scores.Length; i++)
{
    Console.WriteLine($"第{i+1}个成绩:{scores[i]}");
}

// 多维数组
int[,] matrix = new int[3, 3];  // 3x3矩阵
matrix[0, 0] = 1;
matrix[1, 1] = 2;

// 交错数组(数组的数组)
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };

2. 集合

csharp 复制代码
using System.Collections.Generic;

// List<T> - 动态数组
List<string> names = new List<string>();
names.Add("张三");
names.Add("李四");
names.Add("王五");

// 遍历List
foreach (string name in names)
{
    Console.WriteLine(name);
}

// Dictionary<TKey, TValue> - 字典/哈希表
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("张三", 85);
scores.Add("李四", 92);
scores["王五"] = 78;  // 另一种添加方式

// 访问字典
if (scores.ContainsKey("张三"))
{
    Console.WriteLine($"张三的成绩:{scores["张三"]}");
}

// Queue<T> - 队列(先进先出)
Queue<string> queue = new Queue<string>();
queue.Enqueue("第一个");
queue.Enqueue("第二个");
string first = queue.Dequeue();  // 取出"第一个"

// Stack<T> - 栈(后进先出)
Stack<string> stack = new Stack<string>();
stack.Push("第一个");
stack.Push("第二个");
string last = stack.Pop();  // 取出"第二个"

四、异常处理

csharp 复制代码
try
{
    // 可能出错的代码
    Console.Write("请输入一个数字:");
    string input = Console.ReadLine();
    
    int number = int.Parse(input);  // 可能抛出FormatException
    
    int result = 100 / number;      // 可能抛出DivideByZeroException
    
    Console.WriteLine($"结果是:{result}");
}
catch (FormatException ex)
{
    Console.WriteLine("错误:输入的不是有效数字!");
    Console.WriteLine($"详细错误:{ex.Message}");
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("错误:不能除以零!");
}
catch (Exception ex)  // 捕获所有其他异常
{
    Console.WriteLine($"发生未知错误:{ex.Message}");
}
finally
{
    // 无论是否发生异常都会执行
    Console.WriteLine("程序执行完毕");
}

// 抛出异常
public int Divide(int a, int b)
{
    if (b == 0)
        throw new ArgumentException("除数不能为零");
    
    return a / b;
}

五、WinForms 特有语法

1. 事件处理

csharp 复制代码
// 事件声明
public event EventHandler ButtonClicked;

// 事件触发
protected virtual void OnButtonClicked(EventArgs e)
{
    ButtonClicked?.Invoke(this, e);  // 安全调用
}

// 事件处理方法
private void Button_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;  // 类型转换
    MessageBox.Show($"你点击了{button.Text}按钮");
}

// 事件订阅
button1.Click += Button_Click;  // 添加事件处理程序
button1.Click += (s, e) => { MessageBox.Show("匿名方法"); };  // 使用lambda表达式

// 取消订阅
button1.Click -= Button_Click;

2. WinForms常用控件

csharp 复制代码
// 创建控件
Button btn = new Button();
btn.Text = "点击我";
btn.Location = new Point(100, 50);
btn.Size = new Size(100, 30);
btn.Click += Btn_Click;  // 关联事件

// 添加到窗体
this.Controls.Add(btn);

// 常用属性和方法
TextBox textBox = new TextBox();
textBox.Text = "输入文本";      // 文本内容
textBox.Multiline = true;        // 多行
textBox.ReadOnly = false;        // 是否只读
textBox.Clear();                 // 清空内容

3. 消息框

csharp 复制代码
// 简单消息框
MessageBox.Show("操作完成!");

// 带标题和按钮的消息框
DialogResult result = MessageBox.Show(
    "确定要删除吗?",              // 消息内容
    "确认删除",                    // 标题
    MessageBoxButtons.YesNo,      // 按钮类型
    MessageBoxIcon.Question);     // 图标

if (result == DialogResult.Yes)
{
    // 用户点击了"是"
}

// 警告框
MessageBox.Show("输入错误!", "警告", 
    MessageBoxButtons.OK, MessageBoxIcon.Warning);

六、实用的代码片段

1. 文件操作

csharp 复制代码
using System.IO;

// 写入文件
string filePath = @"C:\test.txt";
string content = "Hello, World!";

// 方法1:WriteAllText(覆盖写入)
File.WriteAllText(filePath, content);

// 方法2:StreamWriter(追加写入)
using (StreamWriter writer = new StreamWriter(filePath, true))
{
    writer.WriteLine("新的一行");
}

// 读取文件
if (File.Exists(filePath))
{
    // 读取全部内容
    string allText = File.ReadAllText(filePath);
    
    // 逐行读取
    string[] lines = File.ReadAllLines(filePath);
    foreach (string line in lines)
    {
        Console.WriteLine(line);
    }
}

2. 字符串操作

csharp 复制代码
string str = "Hello, C# World!";

// 常用方法
int length = str.Length;                   // 长度:17
string upper = str.ToUpper();              // 转大写
string lower = str.ToLower();              // 转小写
bool contains = str.Contains("C#");        // 是否包含:true
string replaced = str.Replace("World", "China");  // 替换
string[] parts = str.Split(',');           // 分割:[Hello, C# World!]
string trimmed = str.Trim();               // 去除首尾空格
string substring = str.Substring(7, 2);    // 子串:C#

// 字符串插值(C# 6.0+)
string name = "张三";
int age = 20;
string message = $"姓名:{name},年龄:{age}岁";  // 更简洁

// StringBuilder(大量字符串拼接时使用)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    sb.Append(i.ToString());
}
string result = sb.ToString();

3. 日期时间处理

csharp 复制代码
DateTime now = DateTime.Now;               // 当前时间
DateTime today = DateTime.Today;           // 今天日期

// 格式化
string dateStr = now.ToString("yyyy-MM-dd HH:mm:ss");  // 2024-01-15 14:30:25
string shortDate = now.ToShortDateString();            // 2024/1/15
string longDate = now.ToLongDateString();              // 2024年1月15日

// 日期计算
DateTime tomorrow = now.AddDays(1);
DateTime lastWeek = now.AddDays(-7);
DateTime nextMonth = now.AddMonths(1);

// 时间差
TimeSpan diff = tomorrow - now;
double totalHours = diff.TotalHours;

// 只获取日期部分
DateTime dateOnly = now.Date;

七、学习路线建议

第一阶段:基础语法(1-2周)

  1. 变量、数据类型
  2. 运算符、表达式
  3. 控制流程(if、switch、循环)
  4. 数组和字符串

第二阶段:面向对象(2-3周)

  1. 类和对象
  2. 方法、属性、构造函数
  3. 继承、多态
  4. 接口、抽象类

第三阶段:高级特性(3-4周)

  1. 集合和泛型
  2. 异常处理
  3. 委托和事件
  4. LINQ查询

第四阶段:WinForms开发(4-5周)

  1. 窗体设计
  2. 控件使用
  3. 事件处理
  4. 数据绑定

八、练习项目

项目1:计算器

csharp 复制代码
public class Calculator
{
    public double Add(double a, double b) => a + b;
    public double Subtract(double a, double b) => a - b;
    public double Multiply(double a, double b) => a * b;
    public double Divide(double a, double b) => b != 0 ? a / b : throw new DivideByZeroException();
}

项目2:学生管理系统

csharp 复制代码
public class StudentManager
{
    private List<Student> students = new List<Student>();
    
    public void AddStudent(Student student) => students.Add(student);
    public void RemoveStudent(string studentId) => students.RemoveAll(s => s.StudentId == studentId);
    public Student FindStudent(string name) => students.FirstOrDefault(s => s.Name.Contains(name));
    public List<Student> GetAllStudents() => new List<Student>(students);
}

项目3:记事本应用

  • 使用TextBox实现文本编辑
  • 菜单栏:文件(新建、打开、保存)
  • 编辑(复制、粘贴、查找)
  • 格式(字体、颜色)

九、学习资源推荐

在线资源

  1. 微软官方文档docs.microsoft.com/zh-cn/dotnet/csharp/
  2. 菜鸟教程www.runoob.com/csharp/csharp-tutorial.html
  3. B站视频教程:搜索"C# WinForms教程"

书籍推荐

  1. 《C#入门经典》
  2. 《C#高级编程》
  3. 《Head First C#》

实践建议

  1. 每天写代码:至少1小时
  2. 做笔记:记录遇到的问题和解决方案
  3. 模仿练习:找开源项目学习
  4. 提问:Stack Overflow、CSDN等社区

十、常见问题解答

Q: var和具体类型有什么区别?

A: var是隐式类型声明,编译器会自动推断类型。建议在类型明显时使用,如var list = new List<string>()

Q: 值类型和引用类型有什么区别?

A: 值类型直接存储数据(int、float等),引用类型存储数据地址(class、string等)。

Q: 什么时候用List,什么时候用数组?

A: 数组大小固定时用数组,需要动态增减元素时用List。

Q: WinForms和WPF有什么区别?

A: WinForms使用传统的GDI+绘图,WPF使用DirectX,更现代化,支持更丰富的界面效果。


记住:编程是一门实践技能,多写代码比只看理论更重要。从简单的程序开始,逐步增加复杂度,遇到问题先尝试自己解决,解决不了再查资料或问人。祝你学习顺利!

相关推荐
野犬寒鸦2 小时前
从零起步学习并发编程 || 第三章:JMM(Java内存模型)详解及对比剖析
java·服务器·开发语言·分布式·后端·学习·spring
xyq20242 小时前
Bootstrap 表格
开发语言
大黄说说2 小时前
TensorRTSharp 实战指南:用 C# 驱动 GPU,实现毫秒级 AI 推理
开发语言·人工智能·c#
范纹杉想快点毕业2 小时前
嵌入式系统架构之道:告别“意大利面条”,拥抱状态机与事件驱动
java·开发语言·c++·嵌入式硬件·算法·架构·mfc
陳10302 小时前
C++:map和set的使用
开发语言·c++
2501_940315262 小时前
【无标题】2390:从字符串中移除*
java·开发语言·算法
lly2024062 小时前
jEasyUI 树形菜单添加节点
开发语言
AI职业加油站2 小时前
Python技术应用工程师:互联网行业技能赋能者
大数据·开发语言·人工智能·python·数据分析
鱼很腾apoc3 小时前
【实战篇】 第14期 算法竞赛_数据结构超详解(下)
c语言·开发语言·数据结构·学习·算法·青少年编程