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 =);
}
}
}
第二个代码片段当我将所有变量设为静态时,它允许音量接受给定的分配,不确定如何解释自己,但有人可以向我解释。
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);
}
}
}
解决方案
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();
}
}
推荐阅读
- nlp - 将拼写错误的单词转换为实际单词
- asp.net - 在容器化的 .NET Framework Web 应用程序中更改配置的最佳方法是什么?
- spring-boot - 管理每个套接字消息的数据库调用 Spring Boot
- django - 如何计算 Django 中两个关系之间的数据?
- python - 如何对热图进行排序以显示最高相关性?
- reactjs - React 测试库 - 屏幕调试提供与浏览器不同的输出
- php - 无法使用 php 插入 MySQL 数据库
- angular - 如何更改角垫扩展面板方向
- electron - 如何检查电子中是否按下了某个键?
- reactjs - 无法使用 Formik 在 FieldArray 中设置FieldValue