【实例】创建用户类 User,并创建构造方法为用户类中的属性赋值。在 Main 方法中 调用输出用户信息的方法,用户属性包括用户名、密码、手机号。

    1. class User
    2. {
    3. public User(string name, string password, string tel) //与类名相同的构造方法
    4. {
    5. this.Name = name;
    6. this.Password = password; //this表示的调用改方法的对象
    7. this.Tel = tel;
    8. }
    9. public string Name { get; set; }
    10. public string Password { get; set; }
    11. public string Tel { get; set; }
    12. public void PrintMsg()
    13. {
    14. Console.WriteLine("用户名:" + this.Name);
    15. Console.WriteLine("密 码:" + this.Password);
    16. Console.WriteLine("手机号:" + this.Tel);
    17. }
    18. }

    在上面程序的构造方法中含有 3 个参数,为每一个属性赋值。这里用“this.属性名”的方式调用属性,this关键字表示当前类的对象。