首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#设置和获取快捷方式属性

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

Stack Overflow用户
提问于 2018-06-20 04:58:42
回答 1查看 994关注 0票数 1

我正在看C#上的一个教学视频,他们显示了一个快捷方式(键入"prop",两次制表符),它会生成以下内容

代码语言:javascript
复制
public int Height { get; set; }

因此,他走了一条捷径,使用=>而不是这个。它试图将两者结合起来,但在长度上得到了错误:

代码语言:javascript
复制
    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运行得很好,但我感兴趣的是,我是否可以像处理长度那样缩短代码。

  1. 我做错了什么,可以这样做吗? 2.有没有更短的方法来设置属性(我在正确的轨道上吗)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-20 05:28:05

在C# 6.0中,您可以使用=> expression-bodied member语法作为只读属性的快捷方式(您不能将它们与set一起使用),而在C# 7.0中,它们被扩展为包括set访问器,就像您在代码中所做的那样(这些访问器需要后备字段,也与您一样)。

很可能是因为您使用的是C#6,所以在set语法上会出现错误。

您问过如何缩短代码,因为您不需要私有的支持成员(您不需要修改setget访问器中的值),因此最短的方法是去掉它们,只使用auto-implemented properties来设置用户可以设置的值。然后,您可以为Volume属性使用=>,因为它应该是只读的(因为它是一个计算字段):

我相信这是您所描述的类的最短代码:

代码语言:javascript
复制
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);
    }

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50936860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档