=>之间的差异;常数{ } =常数

编程入门 行业动态 更新时间:2024-10-25 18:34:36
本文介绍了=>之间的差异;常数{ } =常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在最佳实践和性能(如果有的话)的背景下,什么是更好的方法,以公开在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;之间的差异;常数{ } =常数

本文发布于:2023-08-01 08:55:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常数   差异   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!