不同的吸气剂样式之间的C#差异 [英] Difference in C# between different getter styles
问题描述
有时我会在getter的属性中看到缩写.例如.这两种类型:
I do sometimes see abbreviations in properties for the getter. E.g. those two types:
public int Number { get; } = 0
public int Number => 0;
有人可以告诉我两者之间是否有任何区别.他们的行为如何?它们都是只读的吗?
Can someone please tell me if there are any differences between those two. How do they behave? Are both of them read-only?
推荐答案
是的,它们都是只读的,但是有所不同.在第一个中,有一个后备字段,该后备字段在执行构造函数之前被初始化为0.您可以仅在构造函数中更改值 ,就像常规的只读字段一样. getter本身仅返回该字段的值.
Yes, both of them are read-only, but there is a difference. In the first one, there's a backing field which is initialized to 0 before the constructor is executed. You can change the value only in the constructor, just like a regular read-only field. The getter itself just returns the value of the field.
在第二个中,getter每次都返回0,不涉及任何字段.
In the second one, the getter just returns 0 every time, with no field involved.
因此,要完全避免使用任何自动实现的属性或表达式强成员,我们可以:
So to avoid using any automatically implemented properties or expression-bodied members at all, we have:
第一版
private readonly int _number = 0;
public int Number { get { return _number; } }
第二版
public int Number { get { return 0; } }
下面是一个更清晰的区别示例:
A clearer example of the difference might be seen like this:
public DateTime CreationTime { get; } = DateTime.UtcNow;
public DateTime CurrentTime => DateTime.UtcNow;
如果创建单个对象,则其CreationTime
属性将始终给出相同的结果-因为它存储在只读字段中,并在对象构造时初始化.但是,每次访问CurrentTime
属性时,都会导致对DateTime.UtcNow
进行求值,因此可能会得到不同的结果.
If you create a single object, its CreationTime
property will always give the same result - because it's stored in a readonly field, initialized on object construction. However, every time you access the CurrentTime
property, that will cause DateTime.UtcNow
to be evaluated, so you'll get a potentially different result.
这篇关于不同的吸气剂样式之间的C#差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!