您的位置:首页 > 编程语言 > C#

C# 6 —— 属性

2015-06-24 20:59 465 查看
记录一下 C# 6 有关属性的语法糖实现,C# 6 涉及到属性的新特性主要有 2 个:自动属性初始化、只读属性赋值与读取。

自动属性初始化(Auto-property initializers)

C# 6

// Auto-property initializers
public int Auto { get; set; } = 5;

ILSpy 反编译后的代码

public int Auto { get; set; }

private Program()
{
this.<Auto>k__BackingField = 5;
base..ctor(); // 调用基类构造函数
}

只读属性赋值与读取

涉及到只读属性的赋值与读取的新特性大致有 3 种:

Getter-only auto-properties (类似自动属性初始化)

在构造函数中赋值

表达式式的属性实现

Getter-only auto-properties

C# 6

// Getter-only auto-properties
public int ReadOnly { get; } = 10;

ILSpy 反编译后的代码

public int ReadOnly
{
[CompilerGenerated]
get
{
return this.<ReadOnly>k__BackingField;
}
}

private Program()
{
……
this.<ReadOnly>k__BackingField = 10; // <ReadOnly>k__BackingField 为只读属性
base..ctor();
}

在构造函数中赋值(Ctor assignment to getter-only autoprops)

C# 6

Program(int i)
{
// Getter-only setter in constructor
ReadOnly = i;
}

ILSpy 反编译后的代码

private Program(int i)
{
……
this.<ReadOnly>k__BackingField = 10; // <ReadOnly>k__BackingField 为只读字段
base..ctor();
this.<ReadOnly>k__BackingField = i;
}

表达式式的属性实现(Expression bodies on property-like function members)

C# 6

// Expression bodies on property-like function members
public int Expression => GetInt();

int GetInt()
{
return new Random(10).Next();
}

ILSpy 反编译后的代码

public int Expression
{
// 可知,该属性为只读属性
get
{
return this.GetInt();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: