[英]C# set and get shortcut properties
I'm watching an instructional video on C# and they showed a shortcut (type "prop", tab twice) it generates this 我正在观看有关C#的教学视频,他们展示了一个快捷方式(键入“ prop”,两次选择标签),它会
public int Height { get; set; }
So then he went on a shortcut about using => instead of this. 因此,他继续了使用=>代替此方法的捷径。 It tried to combine the two but got an error in Length:
它试图将两者结合起来,但是在长度上却出现了错误:
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 works fine, but I was interested in seeing if I can shorten the code like I'm trying to do with Length. Volume工作正常,但是我很想知道是否可以像尝试使用Length那样缩短代码长度。
You can use the =>
expression-bodied member syntax as a shortcut for read-only properties in C# 6.0 (you can't use them with a set
) and in C# 7.0 they were expanded to include set
accessors as you have in your code (which require backing fields, also as you have). 您可以使用
=>
表达式主体成员语法作为C#6.0中只读属性的快捷方式(不能将它们与set
一起使用),并在C#7.0中将它们扩展为包含代码中的set
访问器(也需要备份字段)。
Most likely you're on C#6 so you're getting an error on the set
syntax. 很可能您使用的是C#6,因此在
set
语法上遇到错误。
You asked how to shorten your code, and since you don't have a need for a private backing member (you aren't modifying the value in the set
or get
accessors), it would be shortest to get rid of them and just use auto-implemented properties for the ones that the user can set. 您询问了如何缩短代码,并且由于不需要私有支持成员(您无需修改
set
的值或get
访问器),因此摆脱它们并使用它是最短的。用户可以设置的属性的自动实现属性 。 Then you can use =>
for the Volume
property, since it should be read-only (because it's a calculated field): 然后,可以对
Volume
属性使用=>
,因为它应该是只读的(因为它是一个计算字段):
I believe this is the shortest code for the class you've described: 我相信这是您所描述的类的最短代码:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.