gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:48:48 26 4
gpt4 key购买 nike

现在我的问题是,当我创建新的对象类型 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] 但我不确定这是否正确。如果我错了,请随时纠正我。

最佳答案

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

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);
}
}

关于c# - 是否可以使数组大小大小取决于属性值(int)? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com