【发布时间】:2018-06-19 20:58:42
【问题描述】:
我正在观看关于 C# 的教学视频,他们展示了一个快捷方式(键入“prop”,两次制表符)它会生成此内容
public int Height { get; set; }
然后他继续使用 => 而不是这个的捷径。它试图将两者结合起来,但长度出错:
class Box
{
private int length;
private int height;
private int width;
private int volume;
public Box(int length, int height, int width)
{
this.length = length;
this.height = height;
this.width = width;
}
public int Length { get => length; set => length = value; } // <-error
public int Height { get; set; }
public int Width { get; set; }
public int Volume { get { return Height * Width * Length; } set { volume = value; } }
public void DisplayInfo()
{
Console.WriteLine("Length is {0} and height is {1} and width is {2} so the volume is {3}", length, height, width, volume = length * height * width);
}
}
Volume 工作正常,但我很想看看是否可以像我尝试使用 Length 一样缩短代码。
- 我做错了什么,可以那样做吗? 2.是否有更短的设置属性(我在正确的轨道上)
【问题讨论】:
-
似乎对我有用:tio.run/…
-
在当前示例中,您不需要私有
length字段,就像height和width一样,您可以删除私有字段并使用PropertyName { get; set; }的自动属性 -
您可能也不应该为
Volume使用set,因为它是一个计算字段。如果有人更改了Volume,您将如何调整其他尺寸属性? -
对于
Volume,您可能只是指public int Volume => Height * Width * Length; -
@TheLyrist 错误框状态(字段) int Box.length 只有赋值、调用、递减和新对象表达式可以用作语句编辑:我使用的是 C#6。需要升级。
标签: c# properties get set