“this” 关键字
本课属于 Coddy C# 学习旅程的“面向对象编程”单元。第 4 课,共 70 课。
this 关键字指的是类的当前实例。它用于访问实例成员,并区分同名的参数和字段。
使用 this 来区分字段和参数
public class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
}如果没有 this,参数就会遮蔽字段
// 这不会按预期工作
public Person(string name, int age)
{
name = name; // 把参数赋值给了它自己!
age = age; // 把参数赋值给了它自己!
}将 this 与属性一起使用
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public Product(string name, decimal price)
{
this.Name = name;
this.Price = price;
}
public void DisplayInfo()
{
Console.WriteLine($"{this.Name}: ${this.Price}");
}
}使用 this 调用同一个类中的另一个构造函数
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public Rectangle(int width, int height)
{
this.Width = width;
this.Height = height;
}
// 用于正方形的构造函数
public Rectangle(int size) : this(size, size)
{
}
}使用示例:
Rectangle rect = new Rectangle(5, 10);
Rectangle square = new Rectangle(5); // 创建 5x5 的正方形this 关键字始终指向当前对象实例。当参数名与字段名或属性名相同时,它尤其有用,能让代码更清晰,并避免错误。
挑战
中等为 Product 类添加一个构造函数,使用 this 关键字将参数值赋给属性,从而完成该类。还要实现 GetDescription() 方法,并使用 this 访问属性。
GetDescription() 方法应返回:"{Name} costs ${Price}"
亲手试试
using System;
class Program
{
static void Main()
{
string name = Console.ReadLine();
decimal price = decimal.Parse(Console.ReadLine());
Product product = new Product(name, price);
Console.WriteLine($"Product: {product.Name}");
Console.WriteLine($"Price: ${product.Price}");
Console.WriteLine(product.GetDescription());
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: C# 在线编译器