且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-08 13:53:52

第一个使用新的-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.)