在类C#中添加默认值

我有一个简单的控制台程序可以让用户登录,然后让他们在登录后更改用户名和密码。我想将默认登录名设置为“ temp”,将默认密码设置为“ password”。我目前有这个

using System;

namespace Loginer
{
    class Program
    {
        static void Main(string[] args)
        {

            string input_user="";
            string input_pass="";

            Login user = new Login(input_user,input_pass);
            bool success = false;

            while (success != true){
                Console.WriteLine("Please key in your username: ");
                string temp_user = Console.ReadLine();

                input_user=temp_user;
                Console.WriteLine("Please key in your password: ");
                string temp_pass = Console.ReadLine();
                input_pass=temp_pass;


                if (input_user == "temp" && input_pass =="password"){
                    Console.WriteLine("Log in success.\n");
                    success = true;

                }

                else{

                    Console.WriteLine("Unsuccessful login, try again\n");

                }


            }

            Console.WriteLine("Please change your username and password (for first time login only)\n");
            Console.WriteLine("Please key in your new username: ");
            string input_newuser = Console.ReadLine();

            Console.WriteLine("Please key in your new password: ");
            string input_newpass = Console.ReadLine();

            user.Username=input_newuser;
            user.Password=input_newpass;

   }
  }
}

我有这个课:

using System;

namespace Loginer
{
    public class Login
    {
        private string _username;
        private string _password;

        public Login(string username, string password){

            _username=username;
            _password=password;

        }

        public string Username{

            get{return _username;}
            set{_username=value;}
        }

        public string Password{

            get{return _password;}
            set{_password=value;}
        }



    }
}

如何在类中添加默认值,而不是在主程序中添加默认值。

我已经在我的登录课程中尝试过

set{_username="temp";}
set{_password="password";}

但是,只要我输入用户名和密码,我就会覆盖它

评论
oalias
oalias

If you want Login.Username and Login.Password to have some default values, just set some values on the backing fields. Of course you also need a parameterless constructor for those to have an effect:

public class Login
{
    private string _username = "temp";
    private string _password = "password";

    public Login()
    { }
    // ...
}
点赞
评论