自动性能有或没有垫板场 - 偏好? [英] Auto-properties with or without backing field - preference?

查看:214
本文介绍了自动性能有或没有垫板场 - 偏好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,使用自动属性时,编译器创建屏幕后面自己的支持字段。然而,在很多节目,我读了学习,我看到人们明确写入

I know that when using auto-properties, the compiler creates its own backing field behind the screen. However, in many programs I read to learn from, I see people explicitly write

private int _backingField;

public int Property { get { return _backingField; } }



是什么上面之间的差,和下面

What is the difference between above, and below?

public int Property { get; private set; }



据我了解,它的明显,当你确实有在吸气剂的副作用使用属性或二传手,但是这往往并非如此。另外,据我所知,你必须明确地使用结构的情况下,支持字段,你不能访问通过属性及其成员。

I understand that its obvious to use the property when you actually have side-effects in the getter or setter, but that's often not the case. 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.

唯一的区别我一直能够找到的是调用价值的方式是它在定义的类中不同的。它是那么简单的偏好,或者是有调用通过其财产或通过直接访问字段中的值更多的东西? ?
简单的约定

The only difference I have been able to find is that the way of calling the value is different inside the class it is defined in. Is it then simple preference, or is there something more to calling a value through its property or by directly accessing the field? Simple conventions?

推荐答案

有没有这两个片段之间没有太大的区别 - 你不能按引用传递属性例如,但这是罕见的问题。但是,如果您希望字段是只读的,就像这样:

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;

foo.SomeProperty.X = 10;



?如果是这样,我通常避免通过我的结构不变的是一个问题开始:)

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

这篇关于自动性能有或没有垫板场 - 偏好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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