我正在试图弄清楚如何使用具有多个变量的对象填充数组。我需要的是创建一个数组,而不是一个列表(我正在尝试学习数组),并用5个不同的bourbons填充它。是否可以填充数组并将名称,年龄,酒厂存储在一个索引中?例如,
如果我调用了索引0,它将显示:
Name: Black Maple Hill
Distillery: CVI Brands, Inc
Age: 8 years
到目前为止我有这个,其中波本威士忌是来自威士忌的派生类,并在主类中调用一个方法来提示用户输入。
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 ++)
{
}
}
}
答案 0 :(得分:0)
在您的代码中,您尚未定义在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;
}
答案 1 :(得分:0)
@Jonathan。是的,根据我的解释,这是可能的。您可以尝试使用索引器。
Class Bourbon : Whiskey {
public Bourbon this[int index]
{
get {
return bBottles[index];
}
set {
bBottles[index] = value;
}
}
}
答案 2 :(得分:0)
选中此需要创建属性和一个构造函数以满足您的要求。
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;
}
}
}