是否可以使数组大小大小取决于属性值(int)? C#

时间:2017-04-07 16:33:25

标签: c#

现在我的问题是,当我创建新的对象类型Trip时,我该如何才能这样做 arrayOfPeople的值是numberOfRooms的大小吗?

class Trip
{
    private Person[] arrayOfPeople;

    public Person[] arrayOfPeople get { return arrayOfPeople; }
        set { arrayOfPeople = value; }

}

class Ship  
{

    private int numberOfRooms;


    public int NumberOfRooms
    {
        get { return numberOfRooms; }
        set { numberOfRooms = value; }
    }

}

我正在考虑将numberOfRooms设为静态,然后在Trip构造函数中设置arrayOfPeople = new Person [Ship.NumberOfRooms],但我不确定这是不是正确的方法。 如果我错了,请随意纠正我。

2 个答案:

答案 0 :(得分:4)

代码中的注释有助于回答您的问题,因此请查看:)

public class Trip
{
    // Define a constructor for trip that takes a number of rooms
    // Which will be provided by Ship.
    public Trip(int numberOfRooms)
    {
        this.ArrayOfPeople = new Person[numberOfRooms];
    }

    // I removed the field arrayOfPeople becuase if you are just
    // going to set and return the array without manipulating it
    // you don't need a private field backing, just the property.
    private Person[] ArrayOfPeople { get; set; }
}

public class Ship
{
    // Define a constructor that takes a number of rooms for Ship
    // so Ship knows it's room count.
    public Ship(int numberOfRooms)
    {
        this.NumberOfRooms = numberOfRooms;
    }

    // I removed the numberOfRooms field for the same reason
    // as above for arrayOfPeople
    public int NumberOfRooms { get; set; }
}

public class MyShipProgram
{
    public static void Main(string[] args)
    {
        // Create your ship with x number of rooms
        var ship = new Ship(100);

        // Now you can create your trip using Ship's number of rooms
        var trip = new Trip(ship.NumberOfRooms);
    }
}

答案 1 :(得分:2)

Trip创建一个构造函数,该构造函数接受一个整数参数public Trip(int numberOfPeople),然后像你提到的arrayOfPeople = new Person[numberOfPeople]()

那样在数组中新建一个