是否可以使数组大小取决于atribute值(int)?c#

是否可以使数组大小取决于atribute值(int)?c#,c#,C#,现在我的问题是,当我进行新对象类型的Trip时,我如何才能这样做, arrayOfPeople的大小将是多少房间 class Trip { private Person[] arrayOfPeople; public Person[] arrayOfPeople get { return arrayOfPeople; } set { arrayOfPeople = value; } } class Ship { private int numb

现在我的问题是,当我进行新对象类型的Trip时,我如何才能这样做, arrayOfPeople的大小将是多少房间

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

Trip
创建一个构造函数,它接受一个整数参数
public Trip(int numberOfPeople)
,在这个新的数组中,就像你提到的
arrayofppeople=new Person[numberOfPeople]()
代码中的注释有助于回答你的问题,所以,看看吧:)


你可以用一张单子。当你使用“高效”这个词时,它就像一个数组一样高效。它不仅“高效”,因为列表将比本机数组使用更多内存。你的意思是,它与数组一样具有“性能”(这也是不正确的,但性能差异几乎可以忽略不计)。在类定义的顶部声明数据成员可以使代码更具可读性…@SamusArin这是一个观点:),但如果你想将属性放在顶部,那么一定要这样做。如果您希望为每个属性提供私有字段备份,而不管它们是否必要,请尝试:)Visual Studio会以这种方式自动生成类图(字段、属性、方法),而不管它们的词法顺序。我不是说这是一个行业标准,但Visual Studio是相当标准的。@SamusArin这取决于您的Visual Studio设置和您自己/公司的常规标准。我在哪里工作以及如何配置VS是字段->构造函数->属性->方法。我们之所以这样设置是因为我们认为属性是方法(它们是引擎盖下的)。但是,不管你想怎么做,这完全取决于你/你的公司。这个答案没有对错之分。@SamusArin这很好,所有开发人员都应该这样做。然而,类结构与自文档化代码无关。。。自文档化代码是一种编写方法名、变量、类等的实践,它们的名称描述了它们是谁,或者它们做什么,或者它们持有什么数据等等。这里的问题是,您希望您的类结构是一种特定的方式(这是完全可以的),但其他人可能希望它是一种不同的方式(这也是完全可以的)。这就像你更喜欢
number=number+1
number+=1
一样。
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);
    }
}