好的,我刚刚开始使用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);
}
}
}
}
答案 0 :(得分:0)
您的“用户名”属性为int
时应为string
。
此外,该属性的范围是私有的,只能在类的方法中修改。
因此要么将范围设置为公开,要么只使用:
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);
}
}
}
}
答案 1 :(得分:0)
我不确定您面临的问题究竟是什么,但以下内容对您有所帮助:
// 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);
}
}
}