“ =”是什么意思?声明属性时在.Net C#中做什么?

编程入门 行业动态 更新时间:2024-10-18 08:25:25
本文介绍了“ =”是什么意思?声明属性时在.Net C#中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经在.NET 4.6.1 C#项目中看到了这种属性声明

I've seen this kind of property declaration in a .NET 4.6.1 C# project

public object MyObject => new object();

我习惯于声明只读属性,例如:

I'm used to declaring read only properties like this:

public object MyObject { get; }

我知道两者之间存在一些差异(第一个会创建一个新对象),但是我想要更深入的说明以及何时使用它们的一些指示。

I understand that there are some differences between the two (the first one creates a new object), but I would like a deeper explanation as well as some indications of when to use either of them.

推荐答案

第一个使用新的-to-C#-6 表达式主体成员语法。等效于:

The first uses the new-to-C#-6 expression-bodied member syntax. It's equivalent to:

public object MyObject { get { return new object(); } }

第二个也是C#6的也是 -自动实现的只读属性。等效于:

The second is also new to C# 6 - an automatically implemented read-only property. It's equivalent to:

private readonly object _myObject; // Except using an unspeakable name public object MyObject { get { return _myObject; } }

您只能分配给 MyObject 来自声明类中的构造函数,实际上只是分配给该字段。

You can only assign to MyObject from within a constructor in the declaring class, which actually just assigns to the field instead.

(这两个等价物都使用了老式的属性声明,您总是将 get , set 设置为一个或两个都包含代码的块。)

(Both of these "equivalencies" are using old-school property declarations, where you always have get, set or both as blocks containing code.)

更多推荐

“ =”是什么意思?声明属性时在.Net C#中做什么?

本文发布于:2023-11-02 14:10:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552618.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中做   属性   声明   Net

发布评论

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

>www.elefans.com

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