C#使用setter/getter无法正确赋值、读取属性值问题排查
学习Setter和Getter
我正在开发一个控制台应用,需要创建Box类并实例化对象,通过setter和getter设置、读取width、height、length三个属性值。我参考了C#中getter/setter调用的相关实现方案,但代码始终无法正常运行,不清楚哪里编写有误。
我的代码
using System; namespace ClassDemo2 { class Box { private double _width; private double _height; private double _length; public double Width { get { return _width; } set { this._width = Width; } } public double Height { get { return _height; } set { this._height = Height; } } public double Length { get { return _length; } set {this._length = Length; } } public double volume() { return Width * Height * Length; } } public class Program { static void Main(string[] args) { Box box = new Box(); //Set value box.Width = 12; box.Height = 12; box.Length = 12; //Get value double width = box.Width; double height = box.Height; double length = box.Length; Console.WriteLine("Box properties"); Console.WriteLine("Width: {0}", width); Console.WriteLine("Height: {0}", height); Console.WriteLine("Length: {0}", length); Console.WriteLine("Volume: {0}", box.volume()); } } }
控制台运行窗口

问题原因与修复
你的属性set访问器写法错误。
C#属性的set块中,内置关键字value才代表外部传入的赋值内容。你当前写的this._width = Width,是把属性本身的当前值(私有字段_width默认初始值为0)重新赋值给私有字段,赋值逻辑完全没生效——不管你给属性传什么值,私有字段永远是初始的0,最终读出来的长宽高全是0,体积计算结果自然也是0。
把三个属性的set块里的赋值右值换成value即可,修改后的属性代码如下:
public double Width { get { return _width; } set { this._width = value; } } public double Height { get { return _height; } set { this._height = value; } } public double Length { get { return _length; } set { this._length = value; } }
修改后重新运行,就能正确输出设置的长宽高值12,体积计算结果为1728。
内容的提问来源于stack exchange,提问作者kawa
相关产品推荐
相关产品推荐

