c# - 将字符串添加到字符串数组

标签 c#

class Myclass
{
    static string[] user_Name = { "admin", "user1", "user2" };
    static string[] user_Password ={ "admin", "123", "789" };

    public static void Check_Method(string u_name, string u_password)
    {

        for (int i = 0; i < user_Name.Length; i++)
        {
            if (u_name == user_Name[i] && u_password == user_Password[i])
            {
                MessageBox.Show("login successful");
                break;
            }
            else
            {
                if (i == (user_Name.Length - 1))
                    MessageBox.Show("Badshow");
            }
        }
    }
    public static void add_user(string name, string password)
    {
        i=user_Name.Length;
        user_Name[i]=name;
        user_Password[i]=password;
        //here i want to add another user but im unable to find the way
    }
}

但是它给出了一个错误,它在数组的边界之外。

执行此操作最方便的方法是什么?

最佳答案

如果您需要可变大小的存储,请不要使用数组。

使用 List<string>相反 - 它允许您 Add项目。


在您的情况下,您对两个数组的选择是有问题的,因为每个用户都有一个相应的密码 - 总是。这表明您应该有一个自定义类来保存用户/密码对。

有了这样一个类(比如说 User ),你会持有一个 List<User>并简化您的代码。

关于c# - 将字符串添加到字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15232813/

相关文章:

c# - ASP.NET 5 (Core 1.0) 本地化/多语言 Web 应用程序

c# - 输入流格式不正确

c# - 模拟索引属性

c# - 执行 reader 时 count(*) 不起作用

c# - C#错误中的左侧赋值

c# - 使用 WriteableBitmapEx 访问像素颜色时出现 AccessViolationException

c# - 使用 FIFO 进行过滤

c# - 如何从其他表单访问列表

c# - 如何以编程方式将 ListBox.Tooltip 绑定(bind)到 DataTable?

c# - Paypal 自适应支付 - IPN 和成功的返回响应