记录一下 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 种:

  1. Getter-only auto-properties (类似自动属性初始化)
  2. 在构造函数中赋值
  3. 表达式式的属性实现

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();
    }
}

相关文章:

  • 2022-12-23
  • 2021-05-24
  • 2021-12-15
  • 2021-05-19
  • 2021-11-01
  • 2022-12-23
猜你喜欢
  • 2021-10-23
  • 2021-08-01
  • 2021-07-02
  • 2021-10-09
  • 2021-09-11
相关资源
相似解决方案