简体   繁体   English

修剪空白并在C#中返回错误

[英]Trim white space and return errors in c#

I'm moving from PHP (procedural) to C# and I've a number of errors in the following block - what am I doing wrong? 我正在从PHP(过程性)转移到C#,并且在以下块中出现了许多错误-我在做什么错?

Objective is to pass in username and password values, then to trim, validate and return a list of errors (I'm using the dictionary to build an array of errors). 目的是传递用户名和密码值,然后修剪,验证并返回错误列表(我正在使用字典来构建错误数组)。

  1. "The name 'varUserName' does not exist in the current context". “名称'varUserName'在当前上下文中不存在”。
  2. "else" = "Type or namespace definition, or end of file expected". “ 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"); } } } 

Thanks Newbie Matt 谢谢新手马特

The problem is, that you do everything in your class. 问题是,您需要在课堂上做所有的事情。 You can't do logic in your class. 您不能在课堂上做逻辑。 Put your code in a Method. 将您的代码放在方法中。 Like so: 像这样:

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;
    }    

}

You can then call it like that in your code: 然后可以在代码中这样调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM