纯吸气剂自动属性和表达式主体属性有什么区别? [英] What is the difference between getter-only auto properties and expression body properties?

查看:20
本文介绍了纯吸气剂自动属性和表达式主体属性有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#6中,您可以使用仅使用吸气剂的自动属性来简化实现属性。例如,如果我实现抽象的 Stream 类:

In the C# 6, you can can simplify implementing a property by using a getter-only auto property. For example, if I were implementing the abstract Stream class:

public override bool CanRead { get; } = true;

但是我也可以使用表达式主体来编写它,这也是C#6中的新功能:

However I can also write it with an expression body, also new in C# 6:

public override bool CanRead => true;

两者之间有什么区别,什么时候应该使用其中一个?

What is the difference between the two, and when should I use one or the other?

推荐答案

它们是两种不同事物的语法糖。前者初始化一个后备字段,并在字段初始化期间将其设置为赋值右侧的表达式。后者创建一个 get ,它完全符合表达式中的内容。

They are syntactic sugar for two different things. The former initializes a backing field, and sets it to the expression on the right hand side of the assignment during field initialization. The latter creates a get that does exactly what is in the expression.

public override bool CanRead { get; } = true;

等同于

private readonly bool __backingFieldCanRead = true;

public override bool CanRead
{
    get
    {
        return __backingFieldCanRead;
    }
}

public override bool CanRead => true;

等价于

public override bool CanRead
{
    get
    {
        return true;
    }
}

它们的行为不同。第一种情况在创建对象并初始化字段时设置属性的值,另一种情况在每次调用属性的getter时都会评估表达式。在布尔的简单情况下,行为是相同的。但是,如果表达式引起副作用,则情况有所不同。考虑以下示例:

They behave differently. The first case sets the value of the property when the object is created and the field are initialized, the other case evaluates the expression every time the property's getter is invoked. In the simple case of a bool, the behavior is the same. However if the expression causes side effects, things are different. Consider this example:

class Program
{
    static void Main(string[] args)
    {
        var fooBar1 = new FooBar();
        Console.WriteLine(fooBar1.Baz);
        Console.WriteLine(fooBar1.Baz);
        var fooBar2 = new FooBar();
        Console.WriteLine(fooBar2.Baz);
        Console.WriteLine(fooBar2.Baz);
    }
}

public class FooBar
{
    private static int counter;
    public int Baz => counter++;
}

此处打印 0、1、2、3。每次调用属性的getter时,静态 counter 字段都会增加。但是,使用属性初始值设定项:

Here, "0, 1, 2, 3" are printed. The static counter field is incremented every time the property's getter is invoked. However, with a property initializer:

public int Baz { get; } = counter++;

然后打印 0,0,1,1,因为表达式是在对象的构造函数中求值的

Then "0, 0, 1, 1" is printed because the expression is evaluated in the object's constructor.

这篇关于纯吸气剂自动属性和表达式主体属性有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆