【问题标题】:Using Get and Set to set specific array elements [duplicate]使用 Get 和 Set 设置特定的数组元素
【发布时间】:2016-04-17 14:59:50
【问题描述】:

我在使用 C# 完成学校作业时遇到问题。

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

我正在创建一个索引为 25 的 Bottle 类数组。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; }
    }

}

【问题讨论】:

  • 如果你的编译不能成功,你可以告诉我们一个错误。我猜你的代码可以编译,但是当你运行它时,确实会出现错误:a NullReferenceException,原因由 QiMata 解释。

标签: c# arrays get set


【解决方案1】:

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

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

【讨论】:

  • 感谢您的详尽解释!
【解决方案2】:

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

bottles = new Bottle[25];

因此,您必须在使用之前为 bottle[0] 赋值。像这样:

bottles[0] = new Bottle();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 2021-07-05
    • 2021-12-21
    相关资源
    最近更新 更多