How can I access the backing variable of an auto-implemented property?

前端 未结 6 1976
逝去的感伤
逝去的感伤 2020-12-23 02:21

In the past we declared properties like this:

public class MyClass
{
    private int _age;

    public int Age
    {
          get{ return _age;  }
                  


        
6条回答
  •  醉话见心
    2020-12-23 02:49

    This syntax is commonly called "syntax sugar", which means that the compiler takes that syntax and translates it into something else. In your example, the compiler would generate code that looks something like this:

    [CompilerGenerated]
    private int k_BackingField;
    
    public int Age
    {
       [CompilerGenerated]
       get
       {
          return this.k_BackingField;
       }
       [CompilerGenerated]
       set
       {
          this.k_BackingField = value;
       }
    

    Even knowing all of that, you could probably access the backing field directly but that sort of defeats the purpose of using automatic properties. I say probably here because you then depend on an implementation detail that could change at any point in a future release of the C# compiler.

提交回复
热议问题