如何用用户输入的数字填充数组?

本文关键字:填充 数组 数字 何用 用户 输入 | 更新日期: 2023-09-27 18:08:03

好了,伙计们,我刚刚开始学习c#,并试图从c++的基础方面过渡。我不知道如何从用户输入填充数组列表到类。我的代码是这样的:

namespace L1
{
    public class Users
    {
        private int username;

        public Users(string username)
        {
            this.username = username;    
        }
        public string Takename() { return username; }    
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Users> users = new List<Users>();
            for(int i=1; i<=4; i++)
            {
               Console.Write("Enter username: ");
               Users user = new Users();
               user.username= Console.Readline();
               users.Add(user);
            }      
        }               
    }
}

如何用用户输入的数字填充数组?

我不确定你究竟面临的问题是什么,但以下可能会对你有所帮助:

// Renamed to User as we are representing only one user
public class User
{
    // Renamed from userName to Name
    // Made a string to be consistent with the constructor
    // Made it a public property
    public string Name { get; set; }
    public User(string name)
    {
        Name = name;
    }
    public string TakenName() { return Name; }
}
class Program
{
    static void Main(string[] args)
    {
        List<User> users = new List<User>();
        // for loops in c# typically are zero based
        for (int i = 0; i < 4; i++)
        {
            Console.Write("Enter Name: ");
            string name = Console.ReadLine();
            User user = new User(name);
            users.Add(user);
        }
    }
}

你的"username"属性应该是string,而现在是int

而且,该属性的作用域是私有的,只能在类的方法中修改。

所以要么将作用域设置为public,要么直接使用:

User user = new Users(Console.ReadLine());

这是基于我告诉你的固定代码:

namespace L1
{
    public class Users
    {
        private string username;

        public Users(string username)
        {
            this.username = username;    
        }
        public string Takename() { return username; }    
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Users> users = new List<Users>();
            for(int i=1; i<=4; i++)
            {
               Console.Write("Enter username: ");
               Users user = new Users(Console.Readline());
               users.Add(user);
            }      
        }               
    }
}