我正在看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运行得很好,但我感兴趣的是,我是否可以像处理长度那样缩短代码。
发布于 2018-06-20 05:28:05
在C# 6.0中,您可以使用=>
expression-bodied member语法作为只读属性的快捷方式(您不能将它们与set
一起使用),而在C# 7.0中,它们被扩展为包括set
访问器,就像您在代码中所做的那样(这些访问器需要后备字段,也与您一样)。
很可能是因为您使用的是C#6,所以在set
语法上会出现错误。
您问过如何缩短代码,因为您不需要私有的支持成员(您不需要修改set
或get
访问器中的值),因此最短的方法是去掉它们,只使用auto-implemented properties来设置用户可以设置的值。然后,您可以为Volume
属性使用=>
,因为它应该是只读的(因为它是一个计算字段):
我相信这是您所描述的类的最短代码:
class Box
{
public int Length { get; set; }
public int Height { get; set; }
public int Width { get; set; }
public int Volume => Height * Width * Length;
public Box(int length, int height, int width)
{
Length = length;
Height = height;
Width = width;
}
public void DisplayInfo()
{
Console.WriteLine("Length = {0}, Height = {1}, Width = {2}, Volume = {3}",
Length, Height, Width, Volume);
}
}
https://stackoverflow.com/questions/50936860
复制相似问题