=>之间的差异;常数{ } =常数 [英] Difference between => constant to { get; } = constant

查看:118
本文介绍了=>之间的差异;常数{ } =常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最佳实践和性能(如果有的话)的背景下,什么是更好的方法,以公开在C#6+样式属性中作为属性设置或计算一次的值?

In the context of best practice and performance (if any) what is better for exposing a value that is either set or calculated once as a property in C# 6+ style properties?

我正在比较表达式主体属性

public string Name => "bob";

自动属性初始化

public string Name { get; } = "bob";

它对同一件事脱糖吗?我在文档中找不到可以用于我的案例的地方。我很抱歉,如果这样已经包含在SO中,那么搜索将使我无处可去。

Does it desugar to the same thing? I can't find anywhere in the docs that says which to use for my case. I apologise if this is covered already in SO, the search got me no where.

推荐答案

当心!表达式身体属性将在每次被调用时执行表达式! 。您可以在答案的最后部分看到示例。

Beware! expression bodied properties will execute the expression every time they are called! You can see the examples in the last part of my answer.

public string Name => "bob";

public string Name
{
    get
    {
        return "bob";
    }
}

public string Name { get; } = "bob";

private readonly string _name = "bob";

public string Name
{
    get
    {
        return _name ;
    }
}

检查出来自己

当心 - 这里是

请注意,每次调用此属性时,表达式主体都会执行。当它返回一个硬编码值时很好,但是例如,如果它返回一个列表,它将每次都返回一个新列表:

Please note that the expression body will be executed every time you call this property. That's fine when it's returning a hard coded value, but if it's returning a list, for example, it will return a new list every time:

public List<String> Names => new List<String>() {"bob"};

语法糖是:

public List<string> Names
{
    get
    {
        return new List<string>() {"bob"};
    }
}

自动属性初始化不是这种情况:

That is not the case with auto-property initialization:

public List<String> Names { get; } = new List<String>() {"bob"};

这是语法糖吗?

private readonly List<string> _names = new List<string>() {"bob"};

public string Names 
{
    get
    {
         return _names;
    }
}

如您所见,此列表仅被初始化一次。

As you can see, here the list is only initialized once.

检查它自己。

这篇关于=&gt;之间的差异;常数{ } =常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆