本文介绍了“ =”是什么意思?声明属性时在.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#中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:01