[英]C# - How do properties access a private field using getter/setter short hand
I am perplexed as in my spare time I've been reading through C# books to become familiar with the language. 我感到很困惑,因为在业余时间我一直在阅读C#书籍以熟悉该语言。
I stumbled upon the use of properties; 我偶然发现了属性的使用; in this context it is in regards to using a getter/setter for a privately declared field in my class.
在这种情况下,是针对在我的班级中的私有声明字段中使用getter / setter。
This is what I have in my code as to keep it simple: 这就是我在代码中保持简单的原因:
class ClassName
{
private int hWorked = 24;
public int HoursWorked
{
get
{
return hWorked;
}
}
}
Now the book says that: 现在这本书说:
If I use the short hand version -
public int HoursWorked {get;}
- that it is the same as the above code.如果我使用简写版本
public int HoursWorked {get;}
-它与上面的代码相同。
But what I need clarification on is how the shorthand is able to return the hWorked
value without specifying that the hWorked = value
. 但是,我需要澄清的是速记是如何能够返回
hWorked
,而不指定值hWorked = value
。
In simple terms: How does the HoursWorked
getter know to target my privately declared hWorked
. 简单来说:
HoursWorked
getter如何知道以我的私有声明hWorked
为目标。
Well public int HoursWorked {get;}
creates its own backing field and doesn't address hWorked
. 很好的
public int HoursWorked {get;}
创建了自己的后备字段, 但未解决 hWorked
。 The equivalent of the code in the question (shorthand version) is 问题(简写版本)中的代码等效为
class ClassName {
public int HoursWorked { get; } = 24;
}
You can see the backing field with a help of Reflection : 您可以在Reflection的帮助下查看背景字段:
using System.Reflection;
...
var fields = string.Join(", ", typeof(ClassName)
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Select(f => f.Name));
Console.Write(fields);
Outcome (may vary): 结果(可能有所不同):
<HoursWorked>k__BackingField
If you inspect the initial ClassName
implementation you'll get 如果检查初始的
ClassName
实现,您将获得
hWorked
the shorthand version uses a "hidden" variable to store the values in. 速记版本使用“隐藏”变量来存储值。
if you write public int hWorked {get; set;}
如果您编写
public int hWorked {get; set;}
public int hWorked {get; set;}
it reads and writes from a unnamed variable in the background. public int hWorked {get; set;}
它在后台从一个未命名的变量读取和写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.