通过用户输入C#将用户添加到列表中

本文关键字:用户 列表 添加 输入 | 更新日期: 2023-09-27 18:21:51

我有一个users类,我想用它来创建一个用户列表,直到用户不再愿意为止。我不知道如何从控制台获得输入。我已经删除了我的主要代码,因为这是一个混乱的混乱,我更喜欢从头开始。下面是我的用户类。

class Users
{
    List<Users> _userList = new List<Users>();
    private string _name;
    private int _age;
    private string _address;
    private string _phone;
    public Users(string name, int age, string address, string phone)
    {
        _name = name;
        _age = age;
        _address = address;
        _phone = phone;
    }
    public string GetName()
    {
        return _name;
    }
    public void SetName(string name)
    {
        _name = name;
    }
    public int GetAge()
    {
        return _age;
    }
    public void SetAge(int age)
    {
        _age = age;
    }
    public string GetAddress()
    {
        return _address;
    }
    public void SetAddress(string address)
    {
        _address = address;
    }
    public string GetPhone()
    {
        return _phone;
    }
    public void SetPhone(string phone)
    {
        _phone = phone;
    }
}

干杯

通过用户输入C#将用户添加到列表中

首先从Users类中删除List并将其重命名为User。

public class User
{
    private string _name;
    private int _age;
    private string _address;
    private string _phone;
    public User(string name, int age, string address, string phone)
    {
        _name = name;
        _age = age;
        _address = address;
        _phone = phone;
    }
    //...
}

然后在控制台Program类中声明List of User类,并将新用户添加到该列表中。根据用户控制台输入设置用户属性。

List<User> _userList = new List<User>();
static void Main(string[] args)
{
    Console.Write("Name: ");
    string name = Console.ReadLine();
    Console.Write("Age: ");
    int age = int.Parse(Console.ReadLine());
    Console.Write("Address: ");
    string address = Console.ReadLine();
    Console.Write("Phone: ");
    string phone = Console.ReadLine();
    User user = new User(name, age, address, phone);
    _userList.Add(user);
}

首先,请注意List<Users> _userList = new List<Users>();在您的类中是不需要的。你不会在任何地方使用它。List<T>结构是存储多个用户的好方法——只需将T替换为表示用户的类型即可。您应该更改类的名称以表示单个用户(User在这里是个好主意),并在类之外使用List<User>

看看这个人为的例子,其中用户有一个string属性——用户的名称。它使您能够将多个用户添加到具有您选择的名称的列表中,然后在新行中打印每个名称。请注意,我使用了自动实现的属性来存储用户名。

class User
{
    public User(string name)
    {
        Name = name;
    }
    public Name { get; private set; }
}   
public static void Main()
{
    List<User> users = new List<User>();
    bool anotherUser = true;
    while (anotherUser)
    {
        Console.WriteLine("Please specify a name.");
        string userName = Console.ReadLine();
        User user = new User(userName);
        users.Add(user);
        string next = Console.WriteLine("Do you want to add another user (type Y for yes)?");
        anotherUser = (next == "Y");
    }
    Console.WriteLine("'nNames of added users:");
    foreach(User u in users)
    {
        Console.WriteLine(u.Name);
    }
    Console.ReadKey();
}    

当然,你必须扩展这个答案,才能真正得到你想要的。这只是一个参考点。

让我们考虑一个简单的用例来获得基本的理解:

正如其他人已经建议的那样,你可以改进User类,如下所示,C#有一个自动实现属性的概念,编译器将在后台为你处理getter/setter代码的生成,所以至少你的代码足够干净!!同样,有时你可能需要有构造函数注入的属性值或显式方法来设置值,我不打算讨论这个问题。

public class User
{
   public string Name { get; set; }
   public int Age { get; set; }
   //Other properties/indexers/delegates/events/methods follow here as required. Just find what all these members are in C#!!
}

接受用户输入的代码:

static void Main(string[] args)
{
     List<User> users = new List<User>();
     char createAnotherUser = 'N';
     do
     {
          var user = new User();
          int age;
          Console.Write("'nUser Name: ");
          user.Name = Console.ReadLine();
          Console.Write("Age: ");
          string ageInputString = Console.ReadLine();
          //Validate the provided age is Int32 type. If conversion from string to Int32 fails prompt user until you get valid age.
          //You can refactor and extract to separate method for validation and retries etc., as you move forward.
          while (!int.TryParse(ageInputString, out age)) //Notice passing parameter by reference with 'out' keyword and it will give us back age as integer if the parsing is success.
          {
               Console.Write("Enter a valid Age: ");
               ageInputString = Console.ReadLine();
          }
          //Accept other data you need and validate if required
          users.Add(user); //Add the user to the List<User> defined above
          //Confirm if another user to be created
          Console.Write("Do you want to create another User[Y/N]? : ");
          createAnotherUser = char.ToUpper(Console.ReadKey(false).KeyChar); //Compare always upper case input irrespective of user input casing.
    } while (createAnotherUser == 'Y');

您可以在MSDN 中了解有关使用out关键字通过引用传递变量的更多信息

希望这能给你一些想法。。。