【问题标题】:Adding default values in class c#在类 c# 中添加默认值
【发布时间】:2020-05-17 18:27:25
【问题描述】:

我有一个简单的控制台程序让用户登录,然后让他们在登录后更改用户名和密码。我希望将默认登录名设置为“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";}

但是每当我输入用户名和密码时,我都会覆盖它

【问题讨论】:

    标签: c# oop


    【解决方案1】:

    如果您希望Login.UsernameLogin.Password 具有一些默认值,只需在支持字段上设置一些值。当然,你还需要一个无参数的构造函数才能产生效果:

    public class Login
    {
        private string _username = "temp";
        private string _password = "password";
    
        public Login()
        { }
        // ...
    }
    

    【讨论】:

    • 非常感谢。我不知道无参数构造函数,因为我还是 c# 的新手。做了一些阅读并让它工作
    猜你喜欢
    • 2017-12-19
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多