首页 > 解决方案 > 为什么我的 if 语句不起作用?我的代码有什么问题?

问题描述

因此,当我在 EditText 栏中输入正确的凭据时,我仍然会收到 ACCESS DENIED 消息。应该发生的是我应该得到 ACCESS GRANTED 消息而不是 ACCESS DENIED。那么我的 if 语句有什么问题呢?

        LinearLayout layout = new LinearLayout(this);
        layout.Orientation = Orientation.Vertical;

        TextView userText = new TextView(this);
        TextView passText = new TextView(this);

        EditText userInput = new EditText(this);
        EditText passInput = new EditText(this);

        TextView access = new TextView(this);
        access.Text = "";

        Button loginButton = new Button(this);
        loginButton.Text = "Login";

        userText.Text = "Username";
        passText.Text = "Password";

        userInput.SetMaxLines(1);
        passInput.SetMaxLines(1);

        string username = userInput.Text;
        string password = passInput.Text;

        loginButton.Click += (sender, e) =>
        { CheckCredentials(); };

        void CheckCredentials()
        {
            if (username == "Admin" && password == "adminpass")
            {
                access.Text = "ACCESS GRANTED!";
            }
            else
            {
                access.Text = "ACCESS DENIED!";
            }
        }

        SetContentView(layout);
        layout.AddView(userText);
        layout.AddView(userInput);
        layout.AddView(passText);
        layout.AddView(passInput);
        layout.AddView(loginButton);
        layout.AddView(access);

当您将“Admin”作为用户名并将“adminpass”作为密码时,应该打印出 ACCESS GRANTED。

标签: c#xamarin

解决方案


username并且password是空白字符串,因为应用程序启动时文本框是空白的。你需要搬家

string username = userInput.Text;
string password = passInput.Text;

inside ofCheckCredentials检索用户实际输入的内容。


推荐阅读