我正在尝试弄清楚如何用一个具有多个变量的对象填充一个数组。我需要的是创建一个数组,而不是一个列表(我正在尝试学习数组),并用5个不同的波旁填充它。是否可以填充数组并将名称、年龄、酿酒厂存储在一个索引中?例如,
如果我调用index 0,它将显示:
Name: Black Maple Hill
Distillery: CVI Brands, Inc
Age: 8 years到目前为止,我已经有了这个,在这个类中,波旁是一个从whiskey派生的类,并在主类中调用一个方法来提示用户输入。
class Bourbon : Whiskey
{
private Bourbon[] bBottles = new Bourbon[5];
public void bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
}
}
}发布于 2012-11-29 14:33:50
在您的代码中,您还没有定义在for循环中使用的value变量。您可以创建类的新实例,然后将其存储在数组中:
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}还要确保您正确地定义了Bourbon类构造函数:
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}发布于 2012-11-29 14:38:44
@Jonathan。是的,根据我的解释,这是可能的。您可以尝试使用索引器。
Class Bourbon : Whiskey {
public Bourbon this[int index]
{
get {
return bBottles[index];
}
set {
bBottles[index] = value;
}
}
}发布于 2012-11-29 18:14:26
勾选这个需要创建属性和一个构造器来实现你的需求。
class Bourbon
{
private Bourbon[] bBottles = new Bourbon[5];
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string distillery;
public string Distillery
{
get { return distillery; }
set { distillery = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}
}https://stackoverflow.com/questions/13619906
复制相似问题