zoukankan      html  css  js  c++  java
  • C# 6 —— 属性

    记录一下 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();
        }
    }
    
  • 相关阅读:
    MinGW GCC 7.1.0 2017年6月份出炉啦
    java面试题-框架篇九
    spring-AOP原理
    spring的bean管理(注解)
    23种设计模式(1)-单例模式
    SSH框架面试题集锦
    JQuery基础
    实现用户注册
    spring与hibernate的整合
    spring-IOC理解1
  • 原文地址:https://www.cnblogs.com/portal/p/4598629.html
Copyright © 2011-2022 走看看