为什么我不能在类中分配实例成员变量

时间:2019-07-04 19:35:43

标签: c#

当我尝试在体积=长*宽*高的类中分配实例成员变量时的第一个片段。我收到一条错误消息,指出字段初始化程序无法引用非静态字段,方法或属性“ 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 =);
        }
    }
}

当我将all变量设置为静态变量时,第二个代码片段使卷可以接受给定的赋值,不确定如何解释自己,但有人可以向我解释。

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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

@Cacheable