繁体   English   中英

C#设置并获取快捷方式属性

[英]C# set and get shortcut properties

我正在观看有关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那样缩短代码长度。

  1. 我在做什么错,可以这样做吗? 2.设置属性的时间是否短一些(我是正确的人)

您可以使用=> 表达式主体成员语法作为C#6.0中只读属性的快捷方式(不能将它们与set一起使用),并在C#7.0中将它们扩展为包含代码中的set访问器(也需要备份字段)。

很可能您使用的是C#6,因此在set语法上遇到错误。

您询问了如何缩短代码,并且由于不需要私有支持成员(您无需修改set的值或get访问器),因此摆脱它们并使用它是最短的。用户可以设置的属性的自动实现属性 然后,可以对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);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM