简体   繁体   English

将文本框中的字符串添加到数组

[英]Add a string from a textbox to an array

I want to add a string from a textbox to an array, but when I tried to add it to the array it gives me an error (Cannot convert char[] to string[]) what is it that I'm doing wrong, and is it maybe a better way to do it? 我想将文本框中的字符串添加到数组,但是当我尝试将其添加到数组时,它给我一个错误(无法将char []转换为string []),这是我做错了什么,并且这也许是更好的方法吗?

    public string[] users = { "username" };
    public string[] passwords = { "password" };

    string[] users = textBox1.Text.ToArray();
    string[] passwords= textBox2.Text.ToArray();

You want to use char array, not string array. 您要使用char数组,而不是字符串数组。 This is because textBox1.Text returns a string type, not a string array type. 这是因为textBox1.Text返回的是字符串类型,而不是字符串数组类型。 Calling ToArray() on a string results in a char array type. 在字符串上调用ToArray()得出一个char数组类型。

    char[] user = textBox1.Text.ToArray();
    char[] password= textBox2.Text.ToArray();

You should also consider changing string[] user and string[] password to string type instead, since I'm assuming you are only storing one username in user. 您还应该考虑改为将string[] userstring[] password为字符串类型,因为我假设您仅在user中存储一个用户名。 If you are trying to store a collection of users, then you should name your variable correctly, such as string[] users , to not cause confusion. 如果要存储用户集合,则应正确命名变量,例如string[] users ,以免引起混淆。

user and password have been allocated as single element arrays. userpassword已分配为单个元素数组。 Arrays are immutable and cannot be appended to, so you cannot do this: 数组是不可变的,不能附加到数组,因此不能执行以下操作:

public string[] user = { "username" };
public string[] password = { "password" };
//...
user.Append(textBox1.Text);
password.Append(textBox2.Text);

But you could reallocate the user and password arrays with something like this: 但是您可以使用以下方式重新分配userpassword数组:

public string[] user = { "username" };
public string[] password = { "password" };
//...
user = new[] { user[0], textBox1.Text };
password = new[] { password[0], textBox2.Text };

This is rather clumsy, though. 但是,这很笨拙。 You would probably be better off defining user and password as List<String> , ie: 您最好将userpassword定义为List<String> ,即:

public List<string> user = new List<string>() { "username" };
public List<string> password = new List<string>() { "password" };
//...
user.Add(textBox1.Text);
password.Add(textBox2.Text);

You should use char arrays instead of string array : 您应该使用char数组而不是string数组:

public string[] users = { "username" };
public string[] passwords = { "password" };

- -

char[] users = textBox1.Text.ToArray();
char[] passwords= textBox2.Text.ToArray();

And instead of string arrays you can use List<string> for users and passwords. 并且可以使用List<string>代替用户使用的List<string>和密码。

Tip : It's better to rename your textBoxes something like txtUserName for clearify and better code. 提示:最好将文本框重命名为txtUserName之类的txtUserName以使代码更txtUserName ,代码更好。

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

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