C# this 关键字

张开发
2026/4/13 19:09:04 15 分钟阅读

分享文章

C# this 关键字
一.核心定义1.1this是什么this是当前实例对象的引用代码中哪个对象调用方法/属性this就代表哪个对象1.2在哪里用只能在实例成员中使用实例方法构造函数实例属性索引器1.3不能在哪用静态成员中因为静态成员属于类本身不属于某一个具体对象没有当前对象不能用this二.核心用法2.1区分「类成员变量」和「方法参数 / 局部变量」2.1.1 为什么要用当类的成员变量和方法的参数名字完全一样时编译器分不清谁是谁必须用this标记类自己的成员。2.1.2 语法格式this.成员变量名 参数名;this.xxx代表类自己的成员变量 / 属性右侧xxx代表方法传入的参数class Person { // 类的成员变量 private string name; private int age; // 方法参数和成员变量同名 public void SetInfo(string name, int age) { // this.name 是类的成员name 是参数 this.name name; this.age age; } }2.2调用本类的其他构造函数this (参数列表)2.2.1 为什么要用构造函数重载时多个构造函数有重复赋值代码用this(参数)可以复用代码不用重复写。2.2.2语法格式构造函数() : this(传入参数) { // 额外逻辑 }: this(参数)必须写在构造函数声明的末尾先执行被调用的构造函数再执行当前构造函数class Student { public int id; public string name; public int score; // 1. 无参构造调用两参构造 public Student() : this(0, 未知) { } // 2. 两参构造调用三参构造 public Student(int id, string name) : this(id, name, 0) { } // 3. 三参构造核心赋值逻辑 public Student(int id, string name, int score) { this.id id; this.name name; this.score score; } }2.3把当前对象 this 当作参数传递给其他方法3.1.1 用处this就是当前对象本身可以直接作为参数传给其他类 / 方法使用。class Student { public string Name { get; set; } public void ShowMe() { // 把当前对象自己传给工具类方法 StudentTool.Print(this); } } // 工具类 static class StudentTool { public static void Print(Student stu) { Console.WriteLine(stu.Name); } }2.4方法返回 this实现「链式调用」2.4.1用处让方法执行完后返回当前对象自己return this实现连续调用多个方法代码更简洁2.4.2语法格式public 类名 方法名(参数) { // 赋值/逻辑代码 return this; }2.4.3实例class Phone { public string Brand { get; set; } public string Color { get; set; } // 返回this public Phone SetBrand(string brand) { this.Brand brand; return this; } public Phone SetColor(string color) { this.Color color; return this; } } // 链式调用 Phone phone new Phone().SetBrand(苹果).SetColor(白色);2.5扩展方法中的 this 修饰符2.5.1 作用在不修改原有类代码的前提下给已有类型如 string、int、自定义类添加新方法。2.5.2 核心规则扩展方法必须写在静态类中方法本身是静态方法第一个参数必须用this标记「要扩展的类型」2.5.3实例// 扩展方法必须在静态类 static class StringExt { // 给string类型扩展一个转大写的方法 public static string ToUpperStr(this string str) { return str.ToUpper(); } } // 调用像实例方法一样使用 string s hello; string res s.ToUpperStr();2.6索引器中的 this2.6.1 作用让自定义类的对象能像数组一样用[]访问成员索引器的固定写法就是用this。2.6.2 语法格式public 类型 this[int 索引] { get { return 对应值; } set { 赋值; } }2.6.3 示例class MyArray { private int[] arr new int[3]; // 索引器 public int this[int index] { get { return arr[index]; } set { arr[index] value; } } } // 使用 MyArray arr new MyArray(); arr[0] 10; // 本质调用this[0]2.7嵌套类中使用外部类的 this特殊场景了解即可嵌套类无法直接访问外部类的成员需要把外部类的this当前实例传给嵌套类class Outer { public string Name 外部类; public class Inner { public void Show(Outer outer) { Console.WriteLine(outer.Name); } } public void Test() { Inner inner new Inner(); inner.Show(this); // 把外部类对象传给嵌套类 } }三.this关键字易错点静态成员禁止用 this静态方法、静态属性、静态构造函数中绝对不能写this。this 是只读引用不能赋值不能写this new Student();this不能被修改。构造函数的 this () 只能写一次一个构造函数只能通过this调用一个其他构造函数且必须写在最开头。无命名冲突时this 可以省略编译器会自动识别成员变量写不写this.效果一样写this只是更清晰。不能在普通代码块中单独用 this只有在类的实例成员里this才有意义。

更多文章