[英]adding objects in a list, am i doing it right?
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;
}
}
}
adding objects in a list, am i doing it right? 在列表中添加对象,我这样做对吗?
A possible alternative is to let user input all the weights in one go and generate the list: 另一种可能是让用户输入所有的权一气呵成 ,并生成列表:
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();
Some suggestions on Football
class 关于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;
}
}
The adding to the list is right. 添加到列表是正确的。 I would recomend you to use property for the Weight. 我建议您使用属性作为“权重”。
class football
{
public int weight { get; set; }
}
If you dont want to have any code on the get/set. 如果您不想在获取/设置上有任何代码。
public int _weight;
public int weight
{
get
{
//Your Code here
return _weight;
}
set
{
//And Here
_weight = value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.