在C#中创建用户指定的n个对象

时间:2015-03-31 18:56:46

标签: c# variables object

我有一个电梯程序,用户输入要创建的人数。

一旦创建了人数,他们就需要逐个请求升降机。

person对象类的代码是:

class Person
{
    public int currentFloor;
    public int destinationFloor;
    public bool requestMade; // user does not request until inside the lift
    public bool isWaiting;

    // manual
    public Person(int currentFloor, int destinationFloor)
    {
        this.currentFloor = currentFloor;
        this.destinationFloor = destinationFloor;
    }

    // automatic
    public Person()
    {
        var r = new Random();
        currentFloor = r.Next(0, 4); // assign random floor as current (5 lifts)
        assignRandomDestination(); // assign random floor for destination but cannot be the same as current, else randomise destination again
    }

    private void assignRandomDestination()
    {
        var r = new Random();
        destinationFloor = r.Next(0, 4);

        if (destinationFloor == currentFloor)
        {
            assignRandomDestination();
        }
    }

    public void state(Person person, bool waiting)
    {
        if (waiting == true) { person.isWaiting = true; } else { person.isWaiting = false; }
    }

    public bool request()
    {
        return requestMade;
    }
}

我怎么能单独打电话给他们?

1 个答案:

答案 0 :(得分:0)

您应该为Elevator创建另一个Class并添加System.Collections.Generic。

  List<Person> passenger = new List<Person>();

  //Make an Instance of your Person.
  Person my1stperson = new Person();

  //Access their member by dot operator.
  my1stperson.currentFloor = 13;

  //After setting their fields; You can add them to the list by.
  passenger.Add(my1stperson);

  // if you have an Elevator class with currentLocation field on the elevator.

  Elevator.currentLocation = passenger[0].currentFloor; //<- only works if the field is static. Or use the Index. LinQ also works for list. Enumerables etc.

  //If not static, Instantiate the Elevator Class.
  Elevator myElevator = new Elevator();