使用Get和Set来设置特定的数组元素

本文关键字:数组元素 设置 Get Set 使用 | 更新日期: 2024-09-20 21:41:39

我在C#中的学校作业有问题。

我在这里只包括代码的一部分,我希望它足够了。

我正在创建一个Bottle类的数组,索引为25。Bottle类包含三个属性。

现在我需要在数组中获取和设置值,但我无法做到

请参阅下面的示例。我哪里做错了?程序没有显示任何错误,但编译没有成功。如果需要更多的代码,我很乐意提供!

public class Sodacrate
{
    private Bottle[] bottles;
    public Sodacrate() // Constructor for handling new sodas in the soda crate.
    {
        bottles = new Bottle[25];
        bottles[0].Brand = "Fanta";
        bottles[0].Price = 15;
        bottles[0].Kind = "Soda";
    }
}

public class Bottle
{
    private string brand;
    private double price;
    private string kind;
    public string Brand
    {
        get { return brand; }
        set { brand = value; }
    }
    public double Price
    {
        get { return price; }
        set { price = value; }          
    }
    public string Kind
    {
        get { return kind; }
        set { kind = value; }
    }
}

使用Get和Set来设置特定的数组元素

数组的零索引处没有对象。您正在做的是在这里为阵列设置内存:

bottles = new Bottle[25];

然后你要做的是尝试在这个数组中的第一个对象上设置属性:

bottles[0].Brand = "Fanta";
bottles[0].Price = 15;
bottles[0].Kind = "Soda";

缺少以下内容:

bottles[0] = new Bottle();

因此,总结一下你正在做的事情:

//Give me a box big enough to hold 25 bottles
//Set the brand on the first bottle

这就是你应该做的:

//Give me a box big enough to hold 25 bottles
//Put the first bottle in the box
//Set the brand on the first bottle

因为Bottle是一个引用类型,所以该语句将创建一个包含25个元素的数组,其值是引用类型的默认值,为null。

bottles = new Bottle[25];

所以,在使用瓶子[0]之前,你必须给它赋值

bottles[0] = new Bottle();