修剪空格并返回c#中的错误

时间:2016-02-26 10:31:19

标签: c# vs-community-edition

我正在从PHP(程序)转到C#,我在下面的块中遇到了一些错误 - 我做错了什么?

目标是传入用户名和密码值,然后修剪,验证并返回错误列表(我正在使用字典来构建错误数组)。

  1. “当前上下文中不存在名称'varUserName'”。
  2. “else”=“类型或命名空间定义,或预期的文件结尾”。

    public class Login (string InUserName, string InUserPass)
    {
        string varUserName;
        string varUserPass;
    
        // Dictionary object is c# equivalent of PHP's 'array["key"] = "value"'
        Dictionary<string, string> errMsg = new Dictionary<string, string>();
    
        varUserName = "123qwe";
    
        varUserName = varUserName.Trim();
    
        if ((varUserPass == "") && (varUserName == ""))
        {
            errMsg.Add("Username", "Username cannot be blank");
            errMsg.Add("Password", "Username cannot be blank");
        }
        else
        {
            if (varUserName == "")
            {
                errMsg.Add("Username", "Username cannot be blank");
            }
    
            if (varUserPass == "")
            {
                errMsg.Add("Password", "Password cannot be blank");
            }
        }
    }
    
  3. 感谢Newbie Matt

1 个答案:

答案 0 :(得分:1)

问题是,你在课堂上做了一切。你不能在班上做逻辑。将您的代码放在方法中。像这样:

public class Login 
{
    string varUserName;
    string varUserPass;

    // Dictionary object is c# equivalent of PHP's 'array["key"] = "value"'
    Dictionary<string, string> errMsg = new Dictionary<string, string>();

    public Dictionary<string, string> LogMeIn()
    {
        varUserName = "123qwe";

        varUserName = varUserName.Trim();

        if ((varUserPass == "") && (varUserName == ""))
        {
            errMsg.Add("Username", "Username cannot be blank");
            errMsg.Add("Password", "Username cannot be blank");
        }
        else
        {
            if (varUserName == "")
            {
                errMsg.Add("Username", "Username cannot be blank");
            }

            if (varUserPass == "")
            {
                errMsg.Add("Password", "Password cannot be blank");
            }
        }
    return errMsg;
    }    

}

然后您可以在代码中将其称为:

Login login = new Login();
var errMsg = login.LogMeIn();