C#如何声明多个对象?

时间:2019-12-16 10:55:31

标签: c#

我创建了一个房间类(它的长度,宽度,高度为整数),但我想创建2个不同的对象(因为1个声明的类是1个房间,并且程序会询问用户“有多少个房间你想拥有吗?”或类似的东西...)

如何从“房间”类别中创建2个或3个不同的房间?

这是我所拥有的:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Feladatok1_20
{
    public class Exercise55TEST
    {
        public static void exercise()
        {
            System.Console.WriteLine("How many rooms would you like to work in?");
            int numberOfRooms = Int32.Parse(Console.ReadLine());

            List<int> room = new List<int>();

            for (int i = 0; i < numberOfRooms; i++)
            {
                System.Console.WriteLine("How long is the room? (length)");
                int length = Int32.Parse(Console.ReadLine());
                //room.Add(length);

                System.Console.WriteLine("How high is the room? (height)");
                int height = Int32.Parse(Console.ReadLine());
                //room.Add(height);

                System.Console.WriteLine("How wide is the room? (width)");
                int width = Int32.Parse(Console.ReadLine());
                //room.Add(width);

                int area = width*length;
                int wallArea = length*height;
                int ceilingArea = width*length;

                room.Add(area);
                room.Add(wallArea);
                room.Add(ceilingArea);

            }

        }
    }
}

这是我上的课:

namespace Feladatok1_20
{
    public class Exercise55
    {
        public int length;

        public int height;
        public int width;


    }
}

2 个答案:

答案 0 :(得分:4)

1。重命名您的班级

public class Room
{
    public int length { get; set; }
    public int height { get; set; }
    public int width { get; set; }
    // those can be calculated so I would declare readonly properties with get-only
    public int area { get { return width * length; } }
    public int wallArea { get { return  length * height; } }
}

旁注:wallArea应该

public int wallArea { get { return  2 * ((length * height) + (width * height)); } }

并且天花板的面积等于地板的面积,因此一个属性area就足够了

2。声明房间列表,而不是整数

List<Room> roomList = new List<Room>();

3。为您创建房间

for (int i = 0; i < numberOfRooms; i++)
{
    //Console.ReadLine and int.Parse here 
    roomList.Add(new Room(){ length = inputLength, width = inputWidth, height = inputHeight});

答案 1 :(得分:2)

创建“ Room”类的对象列表,然后在需要添加时添加一个对象,例如:

List rooms<Room> = new List<Room>();
    Console.WriteLine("How many rooms do you want to have?");
    int count = Console.ReadLine(Convert.ToIn16());
 for(int i=0l i<count; i++)
{
rooms.Add(new Room());
}