我知道使用自动属性时,编译器会在屏幕后面创建自己的备份字段。但是,在许多程序中,我读到了学习,我看到人们明确地写作

private int _backingField;

public int Property { get { return _backingField; } }
.

以上的差异是什么,低于?

public int Property { get; private set; }
.

我明白在Getter或Setter中实际上具有副作用时,它很明显使用该属性,但这通常不是这种情况。此外,我明白你必须在结构的情况下明确使用备份字段,您无法通过属性访问其成员。

我能找到的唯一区别是调用该值的方式在它定义的类内不同。它是简单的偏好,或者有更多才能通过其属性调用值直接访问该字段? 简单的约定?

有帮助吗?

解决方案

There's not much difference between those two snippets - you can't pass a property by reference, for example, but that's rarely an issue. However, if you want the field to be readonly, like this:

private readonly int _backingField;    
public int Property { get { return _backingField; } }

then there's a difference. The code I've written above prevents the value from being changed elsewhere within the class, making it clear that this is really meant to be immutable. I'd really like to be able to declare a read-only field with a read-only automatically implement property, settable only within the constructor - but that's not available at the moment.

This is rather confusing, by the way:

Also, I understand that you have to explicitly use the backing field in the case of structs, you can't access their members via properties.

What do you mean? You can definitely use properties within structs. Are you talking about backing fields which are mutable structs, i.e. the difference between:

foo.someField.X = 10;

and

foo.SomeProperty.X = 10;

? If so, I normally avoid that being an issue by making my structs immutable to start with :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top