C# 为什么不能在类中指定实例成员变量
当我试图在一个volume=length*width*height的类中分配一个实例成员变量时的第一个snipet。我收到一个错误,说明字段初始值设定项不能引用非静态字段、方法或属性Box.heightC# 为什么不能在类中指定实例成员变量,c#,C#,当我试图在一个volume=length*width*height的类中分配一个实例成员变量时的第一个snipet。我收到一个错误,说明字段初始值设定项不能引用非静态字段、方法或属性Box.height namespace Myproject { class Box { public int length; public int height; public int width; public int volume
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);
}
}
}
第三个问题:为什么只有在am方法中才允许将体积分配给变量进行计算
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);
}
}
}
请不要张贴这样的照片。做其他事情。描述一下。包括代码。无论您希望别人阅读什么,请将其作为文本包含。您是否尝试使用属性?将代码作为文本而不是图像发布到此处。public int Volume{get=>length*width*height;}并遵循@ScottHannen advice对卷的赋值是“初始化”:在创建实例时发生一次。但是“高度”和“宽度”等在当时还没有值,所以编译器不允许您这样做。无论如何,这只会发生一次——这只是一次任务。凯文的建议将音量变成了一种“属性”:它不仅仅是一种价值;它的代码可以在每次查看时计算一个值。我想这就是你真正想要的。您好,但是为什么当变量变为静态时它允许初始化?卷也接受给定的赋值,但是当它是实例变量时,我可以赋值的唯一方法是通过方法、构造函数或属性。为什么是这样,为什么我不能将卷作为实例成员变量赋值。
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();
}
}