简体   繁体   English

C# - 类实例化其他类?

[英]C# - class instantiating other classes?

I'm a C# beginner and am struggling a little bit with how classes relate to one another. 我是一个C#初学者,我正在努力解决课程彼此之间的关系。

I am trying to code up a very simple elevator simulation. 我正在尝试编写一个非常简单的电梯模拟。 I have a class for Elevator: 我有一个电梯班:

class Elevator
{
    public int currentFloor;

    public Elevator()
    {
        currentFloor = 0;
    }

    public void ascend()
    {
        currentFloor++;
    }

    public void descend()
    {
        currentFloor--;
    }
}

Very simple. 非常简单。 This works, I can instantiate a new elevator object and have it go up and down, etc... 这是有效的,我可以实例化一个新的电梯对象并使其上下移动等...

Now, I want to create a building object, so I created a new class for Buildings. 现在,我想创建一个建筑物对象,所以我为建筑物创建了一个新类。 However, I am now stuck - how do I add variable amounts of elevator objects to my buildings? 但是,我现在卡住了 - 如何在建筑物中添加可变数量的电梯对象? For example, I might want to instantiate a building with 3 elevators, or another with 5... 例如,我可能想要实例化一个带有3个电梯的建筑物,或者另一个带有5个电梯的建筑物......

I started creating a solutiomn where the building class has a List of elevators I can dynamically add to, but that seems so obtuse. 我开始创建一个解决方案,其中建筑类有一个我可以动态添加的电梯列表,但这看起来很钝。 So what I am looking for is something like: 所以我要找的是:

Building office = new Building();
office.elevator1 = new Elevator();
office.elevator2 = new Elevator();

which obviously doesn't work because I don't have elevator1 and elevator2 declared in the Building class. 这显然不起作用,因为我没有在Building类中声明的elevator1和elevator2。 What is the best/cleanest way to accomplish what I am looking to do? 完成我想做的最好/最干净的方法是什么? Also, what is this called? 还有,这叫什么? I Googled a ton of terms - class belongs to another class, instantiating a class from another class, similar terms with object instead of class... I've also looked over some of the elevator simulator code out there, but couldn't find anything dynamic like I'm looking for... 我用Google搜索了大量的术语 - 类属于另一个类,从另一个类实例化一个类,与对象而不是类相似的术语......我也看了一些电梯模拟器代码,但找不到像我正在寻找的任何动态......

Having a List<Elevator> is quite appropriate here; 拥有List<Elevator>非常合适; it describes the real-world model very well. 它很好地描述了现实世界的模型。

Perhaps it would be better if it were an Elevator[] (in the sense that perhaps it should not be possible to change the number of installed elevators after the building has been erected), but that's not absolute. 也许如果它是Elevator[] (在某种意义上也许不可能在建筑物竖立后改变已安装的电梯的数量)会更好,但这不是绝对的。

In any case, the collection of elevators should be exposed as a read-only property of appropriate type because it doesn't make sense to swap it with another one. 在任何情况下,电梯的集合都应该作为适当类型的只读属性公开,因为将它与另一个交换是没有意义的。

You can add member of type equal to List<Elevator> nd inject inside constructor 您可以在构造函数中添加类似于List<Elevator> nd inject的类型的成员

Sample 样品

public class Building
{
    private List<Elevator> yourList;
    public Building(List<Elevator> value)
    {
      yourList = value;
    }
}

Use case : 使用案例:

var list = new List<Elevator>();
list.Add
.....
var building = new Building(list);

Here's an alternative: 这是另一种选择:

class Building
{
   public List<Elevator> Elevators { get; set; }

   public Building(params Elevator[] elevators)
   {
       Elevators = elevators.ToList();
   }
}

The you can do: 你可以这样做:

var building = new Building(new Elevator(), new Elevator(), new Elevator());

And add more later: 并在以后添加更多:

building.Elevators.Add(new Elevator());

Depends. 要看。 Say your building will only ever have one elevator. 假设你的建筑只有一部电梯。 You'd want to do something like this: 你想做这样的事情:

public class Building
{
    public Elevator Elevator { get; set; }
}

Then when you create the building like you did in your code above, you can do something like this: 然后,当您像上面的代码中那样创建建筑时,您可以执行以下操作:

office.Elevator = new Elevator();

You're new to C#, so you may not have really been exposed to Properties yet ( more reading ). 你是C#的新手,所以你可能还没有真正接触到Properties更多阅读 )。 Cliffs on Properties: they're creating a way for you to get and set data about your object. 在性能悬崖:他们正在创建一个方法可以让你获取和设置的对象数据。 In this example, we're getting/setting the Elevator . 在这个例子中,我们正在设置/设置Elevator

Now, if your building is going to have an unknown amount of elevators, you can't just write properties for Elevator1 to ElevatorInfinity. 现在,如果您的建筑物将拥有未知数量的电梯,您不能只将Elevator1的属性写入ElevatorInfinity。 That's when you'll want to use a collection of some sort. 那时候你会想要使用某种类型的集合。 As others have posted in here, you can do this like so: 正如其他人在这里发布的那样,你可以这样做:

public class Building
{
    public IList<Elevator> Elevators { get; set; }
}

And to add an elevator to your building: 并为您的建筑添加电梯:

// Make sure you instantiate the list! For practice, you should run this code without instantiating the list, so you can see what happens.
office.Elevators = new List<Elevator>();
office.Elevators.Add(new Elevator());

More reading on IList 更多关于IList的阅读

I think you can override indexer. 我认为你可以覆盖索引器。 Of course, you should backbone it with List. 当然,你应该用List作为主干。 Lists are ok. 列表没问题。

namespace Tests_CSharp_Indexer
{
class Elevator
{
}

class Building
{

    public class ElevatorList
    {
        private List<Elevator> elevators = new List<Elevator>();

        public Elevator this[int i]
        {
            get
            {
                return elevators[i];
            }

            set
            {
                if (i == elevators.Count)
                {
                    elevators.Add(value);
                }
                else
                {
                    elevators[i] = value;
                }
            }
        }

        public int Count {
            get
            {
                return elevators.Count;
            }
        }
    }

    public readonly ElevatorList Elevators = new ElevatorList();

}

class Program
{
    static void Main(string[] args)
    {

        Building building = new Building();

        building.Elevators[0] = new Elevator();
        building.Elevators[1] = new Elevator();
        building.Elevators[2] = new Elevator();

        Console.Out.WriteLine(building.Elevators.Count);
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM