【问题标题】:Adding users to a list via user input C#通过用户输入 C# 将用户添加到列表
【发布时间】:2015-11-14 11:53:03
【问题描述】:

我有一个用户类,我想用它来创建用户列表,直到用户不再希望为止。我不知道如何从控制台获取输入。我已经删除了我的主要代码,因为它是一个令人困惑的混乱,并且宁愿从头开始。我的用户类在下面。

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

}

干杯

【问题讨论】:

  • 控制台应用程序?
  • 什么样的用户输入?安慰 ?桌面?
  • 对不起,是控制台@saranshkataria
  • 看起来很基本的一个例子。你写的哪些代码不起作用?
  • @saranshkataria 我目前没有,我摆脱了它,因为我想了解它是如何工作的。这是一大堆代码,我确信不需要。我想要的只是有一个while循环,添加用户直到用户不想再添加。至少可以说是相当令人沮丧的

标签: c# list class input


【解决方案1】:

首先从您的用户类中删除列表并将其重命名为用户。

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

    //...
}

然后在控制台程序类中声明用户类列表并将新用户添加到列表中。根据用户控制台输入设置用户属性。

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

【讨论】:

  • 感谢您的回答,但我正在尝试将其作为控制台应用程序而不是 Windows 窗体来完成
【解决方案2】:

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

看看这个人为的例子,其中用户有一个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();
}    

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

【讨论】:

    【解决方案3】:

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

    正如其他人已经建议的那样,您可以改进 User 类,如下所示,C# 有一个 Auto-Implemented Properties 的概念,编译器将为您处理幕后的 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');
    

    您可以使用out keyword in MSDN 了解有关通过引用传递变量的更多信息

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

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 1970-01-01
      • 2017-08-18
      • 2015-11-21
      • 2021-05-23
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      相关资源
      最近更新 更多