namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("how many footballs would you want?");
int amount = int.Parse(Console.ReadLine());
List<football> ballist = new List<football>();
for (int i = 0; i < amount; i++)
{
Console.WriteLine("how much should football {0} weigh?", i+1);
int weight = int.Parse(Console.ReadLine());
ballist.Add(new football(weight));
}
Console.WriteLine("amount of footballs is {0}", amount);
ballist.ForEach(s => Console.WriteLine(s.GetWeight()));
Console.ReadLine();
}
}
class football
{
private int weight = 0;
public int GetWeight()
{
return weight;
}
public football(int weigh)
{
weight = weigh;
}
}
}
在列表中添加对象,我做得对吗?
答案 0 :(得分:1)
一种可能的替代方法是让用户输入所有权重一次并生成列表:
Console.WriteLine("please, input footballs' weights separated by comma");
String input = Console.ReadLine();
List<football> ballist = input
.Split(',')
.Select(item => new football(int.Parse(item)))
.ToList();
关于Football
类
// We usually start classes with capital letter
class Football {
private int m_Weight;
// C# is not Java, so use properties, which are more readable
public int Weight {
get {
return m_Weight;
}
private set {
// validate input
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
m_Weight = value;
}
}
// "weight" - let argument correspond to property
public football(int weight) {
Weight = weight;
}
}
答案 1 :(得分:0)
添加到列表是正确的。我建议你使用属性作为权重。
class football
{
public int weight { get; set; }
}
如果你不想在get / set上有任何代码。
public int _weight;
public int weight
{
get
{
//Your Code here
return _weight;
}
set
{
//And Here
_weight = value;
}
}