首页 > 解决方案 > C# - 如何将数组中的元素传递给类中的属性

问题描述

我正在创建一个程序,该程序将根据发送到长度、宽度和高度属性的值计算房间大小。我已将值存储在名为 roomArray 的数组中,该数组存储 4 个房间大小的长度、宽度和高度。我需要将这些值发送到房间类中的属性,因为它可以返回房间大小和粉刷房间所需的油漆加仑数。数组中的元素按长度、宽度和高度的顺序存储。我被卡住了,因为我不知道如何从数组中发送元素。目标是将所有测量结果传递到阵列中的 4 个房间,输出将显示房间的总面积和每个房间需要油漆的加仑数。任何帮助将不胜感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using static System.Array;

namespace PaintingRoomDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Room aRoom = new Room();
            int[,] roomArray = { {12, 10, 9},
                                 {11, 8, 12 },
                                 {10, 10, 8 },
                                 {15, 12, 10} };

            Write("The room area is: {0} gallons of paint needed is {1}",
                aRoom.WallArea, aRoom.GallonsOfPaint);
            ReadLine();
        }
    }
    class Room
    {
        public int Length { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public int WallArea
        {
            get { return CalcWallArea(); }
        }
        public int GallonsOfPaint
        {
            get { return CalcAmountOfPaint(); }
        }
        private int CalcWallArea()
        {
            // I am assuming this calculation is correct for your needs.
            return (Length + Width + Length + Width) * Height;
        }
        private int CalcAmountOfPaint()
        {
            var area = WallArea;
            if (area <= 350)
                return 1;

            int x = 0;
            while (area > 0)
            {
                x++;
                area -= 350;
            }
            return x;
        }
    }
}

标签: c#

解决方案


你为什么不创建一个房间数组呢?像这样。

Room[] rooms = new Room[4] {
   new Room(1, 5, 9),
   new Room(12, 35, 9),
   new Room(18, 25, 9),
   new Room(1, 5, 19)
};

推荐阅读