简体   繁体   English

自动实施的属性-隐藏成员的签名

[英]Auto-Implemented Property - signature of hidden member

When creating an auto-implemented property, C# generates a member for that property somewhere in the background. 创建自动实现的属性时,C#在后台某个位置为该属性生成一个成员。 I for the life of me can't remember what this is called, or what the naming convention for the member is called. 我一辈子都记不起这叫什么,或者该成员的命名约定叫什么。 After Googling for a while, I thought it might be an idea to just ask. 谷歌搜索了一段时间之后,我认为问问可能是一个主意。

Property: 属性:

public int Age { get; set; }

My guess (from memory) of the hidden member: 我对隐藏成员的猜测(从内存中):

private int i_age;

Edit #1 编辑#1

To clarify, I was looking for the term of the auto generated member, which was answered by Dmitry Bychenko below. 为了澄清起见 ,我正在寻找自动生成的成员的术语,下面由Dmitry Bychenko回答。 The term is "backing field" 术语是“后备领域”

Why not carry out a simple experiment ? 为什么不进行简单的实验

using System.Reflection;

...

public class Experiment {
  public int Age { get; set; }
}

...

var fieldNames = string.Join(", ", typeof(Experiment)
    .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
    .Select(field => field.Name));

Console.Write(fieldNames);

Outcome: 结果:

<Age>k__BackingField

Please, notice that unlike i_age actual field's name <Age>k__BackingField doesn't conflict with any field (we can't declare a field with such a name) 请注意,与i_age实际字段的名称<Age>k__BackingField 不同 ,该字段与任何字段冲突 (我们不能使用这样的名称声明字段)

Hi You may want to try this. 您好,您可能想尝试一下。

private int i_age;
public int Age 
{ 
    get {return i_age;} 
    set {i_age = value;}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM