如何验证数据

时间:2017-05-22 20:32:50

标签: c#

我有一个名为UserInfo的类,其中有两个属性Name和ID。

class UserInfo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    } 

并且我还有一个名为UserAlreadyLoggedInException的自定义异常类,当有人尝试使用已经被某人使用的名称时,该异常类在我的main方法中调用。

class UserAlreadyLoggedInException : Exception // 
{
    public UserAlreadyLoggedInException() : base()
    {

    }
    public UserAlreadyLoggedInException(string message) : base(message)
    {

    }
    public UserAlreadyLoggedInException(string message,Exception innerException) : base(message,innerException) 
    {

    }

这是我的main方法。

try
        {
            UserInfo[] Ui = new UserInfo[3];
            Ui[0] = new UserInfo();
            Ui[1] = new UserInfo();
            Ui[2] = new UserInfo();
            for (int i = 0; i < 3; i++)
            {
                Ui[i].Id = i;
                Console.WriteLine("Please inter the name of " + (i+1) + " user");
                if (i == 0)
                {
                    Ui[i].Name = Console.ReadLine();
                }
                else
                {
                    Ui[i].Name = Console.ReadLine();
                    if (Ui[i].Name.Equals(Ui[i - 1].Name))
                    {
                        throw new UserAlreadyLoggedInException("UserName Has already taken");
                    }
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.GetType().Name + ex.Message);
            Console.ReadLine();
        }

当[0]索引对象调用它时,有3个UserInfo类对象直接接受没有任何逻辑的输入,因为它是第一个对象。 当[1]索引调用它将进入else语句,因为我这里是= 1,所以它将接受输入并将其与(i-1)比较为零索引,如果名称存在则会引发异常。如果名称不匹配,循环将继续,这次i将变为2,现在它将再次进入else语句并接受输入,但是问题在这里......现在它将与它进行比较(i - 1)现在变为[1]索引..所以它将第二个索引的名称与第一个索引进行比较,但不与0索引进行比较.... 我如何将它与所有索引进行比较???

2 个答案:

答案 0 :(得分:1)

你可以把你的

if (Ui[i].Name.Equals(Ui[i - 1].Name)){
    throw ...
}

代码进入一个从0开始的循环 - > (i - 1)。

所以你有

for (int j = 0; j < i; j++) {
    // (if logic from above, but j instead of (i - 1))
}

答案 1 :(得分:1)

在将名称分配给任何项目之前,您只需检查整个数组的名称即可。如果您将Any()添加到文件中,则可以使用true扩展方法,如果数组中的任何项与条件匹配,则返回else { string name = Console.ReadLine(); // Before assigning the name to any item, see if it already exists if (Ui.Any(user => user.Name == name)) { throw new UserAlreadyLoggedInException("UserName Has already taken"); } // NOW assign the name Ui[i].Name = name; }

{{1}}