C#基础编程核心知识点总结

一、C# 基础编程

1. 数据类型
  • 值类型 :直接存储数据值,存储在栈中。 示例:int a = 10;(整数)、bool flag = true;(布尔)、char c = 'A';(字符)、struct Point { public int X; public int Y; }(结构体)。

  • 引用类型 :存储数据的引用(地址),数据本身在堆中。 示例:string str = "hello";(字符串)、object obj = new object();(对象)、int[] arr = new int[5];(数组)、List<int> list = new List<int>();(集合)。

  • 指针类型 :存储内存地址,需在unsafe上下文使用(多用于底层操作)。 示例:

    复制代码
    unsafe {
        int a = 10;
        int* p = &a; // 指针p指向a的地址
        Console.WriteLine(*p); // 输出10
    }
  • 可空类型 :允许值类型接收null,语法为类型?(本质是Nullable<T>结构体)。 示例:int? age = null;(整数可空)、bool? isMarried = null;(布尔可空)。 注意:通过HasValue判断是否有值,Value获取值(如if(age.HasValue) Console.WriteLine(age.Value);)。

2. 语句
  • 控制语句

    • if-else

      复制代码
      int score = 85;
      if (score >= 90) Console.WriteLine("优秀");
      else if (score >= 60) Console.WriteLine("及格");
      else Console.WriteLine("不及格");
    • switch-case

      复制代码
      char grade = 'B';
      switch (grade) {
          case 'A': Console.WriteLine("90-100"); break;
          case 'B': Console.WriteLine("80-89"); break;
          default: Console.WriteLine("其他"); break;
      }
    • 循环语句

      • for:for (int i = 0; i < 5; i++) Console.WriteLine(i);

      • while:int j = 0; while (j < 5) { Console.WriteLine(j); j++; }

      • do-while:int k = 0; do { Console.WriteLine(k); k++; } while (k < 5);

    • 跳转语句

      • continue(跳过本次循环):for (int i = 0; i < 5; i++) { if (i == 2) continue; Console.WriteLine(i); }(不输出 2)

      • break(退出循环):for (int i = 0; i < 5; i++) { if (i == 2) break; Console.WriteLine(i); }(只输出 0,1)

      • goto(跳转到标签):goto End; ... End: Console.WriteLine("结束");(慎用,易破坏逻辑)

  • 异常捕获语句(try-catch-finally)

    复制代码
    try {
        int result = 10 / 0; // 引发除零异常
    } catch (DivideByZeroException ex) {
        Console.WriteLine("错误:" + ex.Message); // 捕获特定异常
    } catch (Exception ex) {
        Console.WriteLine("其他错误:" + ex.Message); // 捕获所有异常(父类)
    } finally {
        Console.WriteLine("无论是否异常,都会执行"); // 释放资源等操作
    }
  • using 语句 :自动释放实现IDisposable接口的资源(如文件流、数据库连接)。

    复制代码
    // 自动调用StreamWriter的Dispose()释放资源
    using (StreamWriter sw = new StreamWriter("test.txt")) {
        sw.WriteLine("Hello World");
    }
3. 容器
  • 数组

    • 一维数组:int[] nums = {1, 2, 3};(长度固定)

    • 多维数组(矩形数组):int[,] matrix = { {1,2}, {3,4} };(matrix[0,1] = 2)

    • 交错数组(数组的数组):int[][] jagged = new int[2][]; jagged[0] = new int[] {1,2}; jagged[1] = new int[] {3};(每行长度可不同)

  • 集合

    • 单列集合(List<T>)

      :动态数组,支持增删改查。

      复制代码
      List<string> names = new List<string>();
      names.Add("张三"); // 添加
      names[0] = "李四"; // 修改
      names.RemoveAt(0); // 删除索引0的元素
      foreach (var name in names) Console.WriteLine(name); // 遍历
    • 双列集合(Dictionary<K,V>)

      :键值对存储,通过键快速访问值。

      复制代码
      Dictionary<int, string> idToName = new Dictionary<int, string>();
      idToName.Add(1, "张三"); // 添加
      Console.WriteLine(idToName[1]); // 访问(输出"张三")
      idToName.Remove(1); // 删除
    • 集合运算

      复制代码
      List<int> a = new List<int> {1, 2, 3};
      List<int> b = new List<int> {3, 4, 5};
      var union = a.Union(b).ToList(); // 并集:{1,2,3,4,5}
      var intersect = a.Intersect(b).ToList(); // 交集:{3}
4. 面向对象编程(OOP)
  • 类与对象:类是模板,对象是类的实例。

    复制代码
    class Person { // 类
        // 字段(成员变量)
        public string name;
        private int age;
        
        // 属性(封装字段,控制访问)
        public int Age {
            get { return age; }
            set { if (value > 0) age = value; } // 验证逻辑
        }
        
        // 构造方法(初始化对象)
        public Person(string name, int age) {
            this.name = name;
            this.Age = age; // 调用属性的setter
        }
        
        // 实例方法(需通过对象调用)
        public void SayHello() {
            Console.WriteLine($"我是{name},年龄{Age}");
        }
        
        // 静态方法(通过类名调用,无this)
        public static void PrintType() {
            Console.WriteLine("这是Person类");
        }
    }
    ​
    // 使用:创建对象
    Person p = new Person("张三", 20);
    p.SayHello(); // 实例方法调用
    Person.PrintType(); // 静态方法调用
  • 方法递归:方法自身调用(解决如阶乘、斐波那契等问题)。

    复制代码
    // 计算n的阶乘
    int Factorial(int n) {
        if (n == 1) return 1; // 终止条件
        return n * Factorial(n - 1); // 递归调用
    }
  • 三大特性

    • 封装 :通过访问修饰符(public/private 等)隐藏内部实现,暴露必要接口(如上述Person类的Age属性)。

    • 继承

      :子类继承父类的成员,实现代码复用。

      复制代码
      class Student : Person { // 继承Person
          public string School { get; set; }
          // 重写父类方法(需父类方法为virtual)
          public override void SayHello() {
              Console.WriteLine($"我是{name},在{School}上学");
          }
      }
    • 多态

      :同一操作作用于不同对象产生不同结果(通过虚方法 + 重写实现)。

      复制代码
      Person s = new Student("李四", 18); // 父类引用指向子类对象
      s.SayHello(); // 调用子类重写的方法,输出"我是李四,在...上学"
  • 特殊类 / 接口

    • 抽象类(abstract)

      :不能实例化,可包含抽象方法(需子类实现)。

      复制代码
      abstract class Shape {
          public abstract double GetArea(); // 抽象方法(无实现)
      }
      class Circle : Shape {
          public double Radius { get; set; }
          public override double GetArea() { return Math.PI * Radius * Radius; }
      }
    • 部分类(partial)

      :将类拆分到多个文件,编译时合并

      复制代码
      // File1.cs
      partial class MyClass { public void Method1() {} }
      // File2.cs
      partial class MyClass { public void Method2() {} }
    • 密封类(sealed) :不能被继承。 sealed class FinalClass { }

    • 接口(interface)

      :纯抽象成员(方法、属性等),类可实现多个接口。

      复制代码
      interface IFly { void Fly(); }
      interface ISwim { void Swim(); }
      class Duck : IFly, ISwim {
          public void Fly() { Console.WriteLine("鸭子飞"); }
          public void Swim() { Console.WriteLine("鸭子游"); }
      }
5. API 操作
  • IO 流(文件读写)

    • File 类(静态方法,简化操作):File.WriteAllText("test.txt", "内容"); string content = File.ReadAllText("test.txt");

    • StreamReader/StreamWriter(逐行读写):

      复制代码
      using (StreamReader sr = new StreamReader("test.txt")) {
          string line;
          while ((line = sr.ReadLine()) != null) Console.WriteLine(line);
      }
  • 线程(Thread)

    复制代码
    using System.Threading;
    // 定义线程执行的方法
    void PrintNumbers() {
        for (int i = 0; i < 5; i++) {
            Console.WriteLine(i);
            Thread.Sleep(100); // 休眠100ms
        }
    }
    // 启动线程
    Thread t = new Thread(PrintNumbers);
    t.Start(); // 线程开始执行
  • Socket 通信(TCP)

    • 服务器:TcpListener server = new TcpListener(IPAddress.Any, 8888); server.Start(); TcpClient client = server.AcceptTcpClient();

    • 客户端:TcpClient client = new TcpClient(); client.Connect("127.0.0.1", 8888);

二、C# 高级编程

1. 委托(delegate)与事件(Event)
  • 委托:类型安全的函数指针,可绑定多个方法(多播委托)。

    复制代码
    // 定义委托(与绑定的方法签名一致)
    delegate void MyDelegate(string msg);
    ​
    void ShowMessage(string s) { Console.WriteLine(s); }
    void LogMessage(string s) { File.AppendAllText("log.txt", s); }
    ​
    // 使用
    MyDelegate del = ShowMessage;
    del += LogMessage; // 多播(绑定多个方法)
    del("Hello"); // 执行所有绑定的方法
  • 事件:基于委托的通知机制,仅能在类内部触发(封装委托)。

    复制代码
    class Button {
        // 定义事件(基于委托)
        public event MyDelegate Click;
        
        // 触发事件(通常私有方法)
        public void OnClick() {
            Click?.Invoke("按钮被点击"); // 若有订阅者则触发
        }
    }
    ​
    // 订阅事件
    Button btn = new Button();
    btn.Click += ShowMessage; // 绑定方法
    btn.OnClick(); // 触发事件,执行ShowMessage
2. 多线程(Thread/Task)
  • Task(推荐,基于线程池,更高效)

    复制代码
    // 启动任务
    Task.Run(() => {
        for (int i = 0; i < 5; i++) {
            Console.WriteLine($"Task: {i}");
            Thread.Sleep(100);
        }
    }).Wait(); // 等待任务完成
  • 前台线程(默认) :程序必须等待其完成才退出;后台线程:程序退出时自动终止。 t.IsBackground = true;(设为后台线程)

3. 匿名函数与 Lambda 表达式
  • 匿名函数:delegate(int x) { return x * 2; }

  • Lambda 表达式(简化匿名函数):

    复制代码
    // 无参数
    Action a = () => Console.WriteLine("Hello");
    // 有参数
    Func<int, int> square = x => x * x; // 输入int,返回int
    Console.WriteLine(square(3)); // 输出9
4. 索引器

允许类像数组一样通过[]访问,常用于集合类。

复制代码
class MyCollection {
    private string[] data = new string[10];
    
    // 定义索引器
    public string this[int index] {
        get { return data[index]; }
        set { data[index] = value; }
    }
}
​
// 使用
MyCollection col = new MyCollection();
col[0] = "第一个元素"; // 调用setter
Console.WriteLine(col[0]); // 调用getter,输出"第一个元素"
5. 反射(Reflection)

动态获取类型信息并操作(如调用方法、访问属性)。

复制代码
Type type = typeof(Person); // 获取Person类型
object obj = Activator.CreateInstance(type, "张三", 20); // 创建实例
MethodInfo method = type.GetMethod("SayHello"); // 获取方法
method.Invoke(obj, null); // 调用方法(输出"我是张三,年龄20")

三、Winform 编程

1. 核心元素
  • 窗体(Form) :程序界面容器,常用事件:Load(加载时)、FormClosing(关闭时)。

  • 控件

    • 输入类:TextBox(输入框)、ComboBox(下拉框)、CheckBox(复选框)。

    • 显示类:Label(标签)、DataGridView(表格)、PictureBox(图像)。

    • 交互类:Button(按钮,Click事件)、MenuStrip(菜单)。

  • 属性示例

    • button1.Text = "确定";(按钮文本)

    • textBox1.ReadOnly = true;(输入框只读)

    • dataGridView1.DataSource = list;(表格绑定数据)

  • 事件示例

    复制代码
    // 按钮点击事件(在设计器中绑定或手动注册)
    private void button1_Click(object sender, EventArgs e) {
        string input = textBox1.Text;
        MessageBox.Show("输入内容:" + input); // 弹窗
    }

四、数据库

1. SQL 语句(以 SQL Server 为例)
  • 增删改查

    • 新增:INSERT INTO Students (Name, Age) VALUES ('张三', 20);

    • 查询:SELECT * FROM Students WHERE Age > 18;

    • 更新:UPDATE Students SET Age = 21 WHERE Name = '张三';

    • 删除:DELETE FROM Students WHERE Id = 1;

  • 多表联查

    • 内连接(取交集): SELECT s.Name, c.CourseName FROM Students s INNER JOIN Scores c ON s.Id = c.StudentId;

    • 左外连接(保留左表所有数据): SELECT s.Name, c.CourseName FROM Students s LEFT JOIN Scores c ON s.Id = c.StudentId;

五、联合编程(Winform + 数据库)

通过SqlConnection连接数据库,实现增删改查。

复制代码
// 连接字符串(SQL Server)
string connStr = "Server=.;Database=TestDB;Integrated Security=True;";
​
// 查询数据并绑定到DataGridView
private void LoadData() {
    using (SqlConnection conn = new SqlConnection(connStr)) {
        conn.Open();
        string sql = "SELECT * FROM Students;";
        SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
        DataTable dt = new DataTable();
        adapter.Fill(dt); // 填充数据
        dataGridView1.DataSource = dt; // 绑定到表格
    }
}
​
// 新增数据(按钮点击事件)
private void btnAdd_Click(object sender, EventArgs e) {
    string name = txtName.Text;
    int age = int.Parse(txtAge.Text);
    using (SqlConnection conn = new SqlConnection(connStr)) {
        conn.Open();
        string sql = $"INSERT INTO Students (Name, Age) VALUES ('{name}', {age});";
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery(); // 执行SQL
        LoadData(); // 刷新表格
    }
}
相关推荐
鱼鱼说测试33 分钟前
postman接口自动化测试
开发语言·lua
從南走到北39 分钟前
JAVA国际版东郊到家同城按摩服务美容美发私教到店服务系统源码支持Android+IOS+H5
android·java·开发语言·ios·微信·微信小程序·小程序
_不会dp不改名_1 小时前
C++ 20: Concepts 与Requires
开发语言·c++20
韭菜钟1 小时前
Qt从qmake迁移到cmake的记录
开发语言·qt
少陵野小Tommy2 小时前
Python能用古诗词数据库做什么7:根据标题、诗句查找诗歌
开发语言·数据库·python
长城20242 小时前
PHP如何使用JpGraph生成3D饼形图?
开发语言·php·jpgraph·3d饼形图
BIGFISH20193 小时前
上下相机引导贴合的标定(绝对坐标方式)
c#
秦禹辰4 小时前
本地Docker部署开源Web相册图库Piwigo与在线远程访问实战方案
开发语言·后端·golang
the beard4 小时前
深入理解Java多线程:状态、安全、同步与通信
java·开发语言
lucky_lyovo5 小时前
大模型部署
开发语言·人工智能·云计算·lua