如何访问一个自动实现的属性的支持变量? [英] How can I access the backing variable of an auto-implemented property?
问题描述
在过去,我们声明如下属性:
In the past we declared properties like this:
public class MyClass
{
private int _age;
public int Age
{
get{ return _age; }
set{ _age = value; }
}
}
现在我们可以做的:
public class MyClass
{
public int Age {get; set;}
}
我的问题是,我怎么能访问私有变量,使用这个符号自动创建的?
My question is, how can I access the private variable that is created automatically using this notation?
我宁愿访问私有变量,而不是公共存取'年龄'。是否有一个默认的表示法访问私有变量,或者它仅仅是不可能的?
I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?
推荐答案
新的自动属性的目的是减少样板代码,你需要写的时候你只需要一个简单的属性,这并不需要在GET或设定任何特殊的逻辑量。
The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set.
如果您要访问这些属性使用私有成员,这通常有几个原因:
If you want to access the private member that these properties use, that's usually for a few reasons:
- 您需要的不仅仅是一个简单的get / set更多 - 在这种情况下,你应该避免使用自动属性此成员
- 您想避免的。通过走吧或设置而直接使用成员的性能影响 - 在这种情况下,我会感到惊讶,如果真有性能损失。简单的get / set成员非常非常容易内联,并在我的(诚然有限)测试中,我还没有发现使用自动属性,直接访问成员之间的差异。
-
您只需要拥有公共读取权限(也就是,只有'得到')和类写成员直接 - 在这种情况下,你可以使用一个私人一套您的自动财产。 。即
- You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.
- You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly.
You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e.
public class MyClass
{
public int Age {get; private set;}
}
这通常包括最原因希望获得直接由自动属性用于支持字段。
This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.
这篇关于如何访问一个自动实现的属性的支持变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!