温馨提示×

C#构造函数中的this关键字如何使用

c#
小樊
81
2024-09-11 01:41:08
栏目: 编程语言

在C#中,this关键字用于引用当前类的实例。它可以在构造函数中使用,以便在创建对象时初始化对象的属性和调用其他构造函数。

以下是在C#构造函数中使用this关键字的一些示例:

  1. 引用当前类的实例属性:
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person()
    {
        this.Name = "Unknown";
        this.Age = 0;
    }

    public Person(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }
}
  1. 调用当前类的其他构造函数:
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person() : this("Unknown", 0)
    {
    }

    public Person(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }
}

在这个例子中,我们使用this关键字调用了另一个构造函数,而不是重复编写相同的代码。这有助于提高代码的可读性和可维护性。

0