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

标签 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] 但我不确定这是否正确。 如果我错了,请随时纠正我。

最佳答案

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

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/

相关文章:

c# - Mono 2.8.1 断言 mono_wsq_count (wsq) == 0

c# - 使用URL在Crystal报表中显示图像

c# - 在没有 Visual Studio 2010 的情况下,我可以在哪里下载 C# 4.0 的编译器?

c# - .NET Remoting 被 WCF 取代了吗?

c# - 使用随机对象生成颜色

c# - RESTful WCF 4 服务中移动客户端的用户身份验证

c# - 给定一个窗口,我如何确定它是否是 winforms 应用程序的一部分?

c# - 是否有针对 ASP.NET Web 窗体的现成角色/成员资格框架?

c# - 使用 WPF 的跨平台应用程序

c# - $在字符串前是什么意思?