【问题标题】:C# set and get shortcut propertiesC# 设置和获取快捷方式属性
【发布时间】: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 一样缩短代码。

  1. 我做错了什么,可以那样做吗? 2.是否有更短的设置属性(我在正确的轨道上)

【问题讨论】:

  • 似乎对我有用:tio.run/…
  • 在当前示例中,您不需要私有 length 字段,就像 heightwidth 一样,您可以删除私有字段并使用 PropertyName { get; set; } 的自动属性
  • 您可能也不应该为Volume 使用set,因为它是一个计算字段。如果有人更改了Volume,您将如何调整其他尺寸属性?
  • 对于Volume,您可能只是指public int Volume =&gt; Height * Width * Length;
  • @TheLyrist 错误框状态(字段) int Box.length 只有赋值、调用、递减和新对象表达式可以用作语句编辑:我使用的是 C#6。需要升级。

标签: c# properties get set


【解决方案1】:

您可以使用 =&gt; expression-bodied member 语法作为 C# 6.0 中只读属性的快捷方式(您不能将它们与 set 一起使用),在 C# 7.0 中它们被扩展为包括 set您在代码中使用的访问器(也需要支持字段)。

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

您询问了如何缩短代码,并且由于您不需要私人支持成员(您没有修改 setget 访问器中的值),因此最短摆脱它们,只需将auto-implemented properties 用于用户可以设置的那些。然后您可以将=&gt; 用于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);
    }

}

【讨论】:

  • 整洁,这使代码更简单。谢谢。编辑:另一位用户确实提到我使用的是旧版本,这就是我收到初始错误的原因。但他被否决并删除了他的答案。
猜你喜欢
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多