首页 > 解决方案 > 为什么我不能在类中分配实例成员变量

问题描述

当我尝试在体积 = 长度 * 宽度 * 高度的类中分配实例成员变量时的第一个片段。我收到一条错误消息,指出字段初始化程序无法引用非静态字段、方法或属性“Box.height”。

namespace Myproject
{
    class Box
    {
        public int length;
        public int height;
        public int width;
        public int volume = length * width * height;
        public void DisplayBox()
        {
            Console.WriteLine("The height of box is length {0} * height {1} * width {2} and volume is {3}", length, height, width, volume =);
        }
    }
}

第二个代码片段当我将所有变量设为静态时,它允许音量接受给定的分配,不确定如何解释自己,但有人可以向我解释。

namespace Myproject
{
    class Box
    {
        public  static int length;
        public static int height;
        public static int width;
        public static int volume = length * width * height;
        public void DisplayBox()
        {
            Console.WriteLine("The height of box is length {0} * height {1} * width {2} and volume is {3}", length, height, width, volume);
        }
    }
}

第三个片段为什么只有在允许将体积分配给变量进行计算的方法中?

namespace Myproject
{
    class Box
    {
        public int length;
        public int height;
        public int width;
        public int volume;
        public void DisplayBox()
        {
            Console.WriteLine("The height of box is length {0} * height {1} * width {2} and volume is {3}", length, height, width, volume = length * width * height);
        }
    }
}

标签: c#

解决方案


class Box
    {
        public int Length { get; set; }
        public int Height { get; set; }
        public int Width { get; set; }
        public int Volume => Length * Width * Height;
        public void DisplayBox()
        {
            Console.WriteLine("The height of box is length {0} * height {1} * width {2} and volume is {3}", Length, Height, Width, Volume);
        }
        public Box(){}
        public Box(int length, int height, int width)
        {
            Length = length;
            Height = height;
            Width = width;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Using custom constructor
            new Box(5,10,4).DisplayBox();
            //Using default constructor
            new Box {Length = 5, Height = 10, Width = 4}.DisplayBox();
            //Using class instance
            var box = new Box();
            box.Length = 5;
            box.Height = 10;
            box.Width = 4;
            box.DisplayBox();
            Console.ReadKey();
        }
    }

推荐阅读