嗯,简单地说,我现在就了解结构(C#的新功能) 这是我的结构(+ ctor)
public struct BusLine
{
public int busNumber { get; set; }
public int passengersNumber { get; set; }
public double drivePrice { get; set; }
public double distanceBeginToEnd { get; set; }
public int stopsNumber { get; set; }
public BusLine(int _busNumber, int _passengersNumber, double _drivePrice, double _distanceBeginToEnd, int _stopsNumber)
{
busNumber = _busNumber;
passengersNumber = _passengersNumber;
drivePrice = _drivePrice;
distanceBeginToEnd = _distanceBeginToEnd;
stopsNumber = _stopsNumber;
}
}
这是我的Bus类
public class Bus
{
public BusLine Line { get; set; }
public int currentPassengers { get; set; }
public int currentStop { get; set; } = 1;
public void EnterStation(int newPassengers, int passengerLeaves)
{
currentPassengers = Line.passengersNumber + newPassengers - passengerLeaves;
}
public string Drive()
{
if (currentStop == this.Line.stopsNumber)
{
return string.Format("Stop number: {0}\nPassengers quantity: {1}\nThis is the final STOP!\n", currentStop, currentPassengers);
}
return string.Format("Stop number: {0}\nPassengers quantity: {1}\n", currentStop++, currentPassengers);
}
}
现在的问题是: 当我以这种方式实例化struct和class时(在Program.cs中):
Random rand = new Random();
BusLine BLine = new BusLine(_busNumber: 88, _passengersNumber: 22, _drivePrice: 6.90, _distanceBeginToEnd: 101.4, _stopsNumber: 15);
Bus bus = new Bus();
while (BLine.stopsNumber != 0)
{
BLine.stopsNumber--;
bus.EnterStation(rand.Next(1, 12), rand.Next(1, 12));
string getDrive = bus.Drive();
Console.WriteLine(getDrive);
}
似乎是这一行(在Bus.cs中):
currentPassengers = Line.passengersNumber + newPassengers - passengerLeaves;
Line.passengersNumber = 0 和
if (currentStop == this.Line.stopsNumber)
永远不会发生,因为this.Line.stopsNumber始终为零 现在我明白使用结构的东西是错误的,但我在BusLine.cs的ctor中初始化它们,那么在Bus.cs中使用时它们的值如何仍为0? 先谢谢你们
答案 0 :(得分:6)
看起来你从未将BLine设置为公交线路。将该总线声明更改为:
Bus bus = new Bus() { Line = BLine };
直到你这样做,BLine与bus.Line无关,只是属于同一类型。