C# Automatic Properties - Why Do I Have To Write “get; set;”?

后端 未结 9 1923
失恋的感觉
失恋的感觉 2020-12-29 01:33

If both get and set are compulsory in C# automatic properties, why do I have to bother specifying \"get; set;\" at all?

9条回答
  •  天涯浪人
    2020-12-29 01:47

    Just thought I would share my findings on this topic.

    Coding a property like the following, is a .net 3.0 shortcut call “auto-implemented property”.

    public int MyProperty { get; set; }
    

    This saves you some typing. The long way to declare a property is like this:

    private int myProperty;
    public int MyProperty 
    {
      get { return myProperty; }
      set { myProperty = value; } 
    }
    

    When you use the “auto-implemented property” the compiler generates the code to wire up the get and set to some “k_BackingField”. Below is the disassembled code using Reflector.

    public int MyProperty
    {
        [CompilerGenerated]
        get
        {
            return this.k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.k__BackingField = value;
        }
    }
    

    disassembled C# code from IL

    Also wires up a method for the setter and getter.

    [CompilerGenerated]
    public void set_MyProperty(int value)
    {
        this.k__BackingField = value;
    }
    [CompilerGenerated]
    public int get_MyProperty()
    {
        return this.k__BackingField;
    }
    

    disassembled C# code from IL

    When you declare a read only auto-implemented property, by setting the setter to private:

     public int MyProperty { get; private set; }
    

    All the compiler does flag the "set" as private. The setter and getter method say the same.

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

    disassembled C# code from IL

    So I am not sure why the framework require both the get; and set; on an auto-implemented property. They could have just not written the set and setter method if it was not supplied. But there may be some compiler level issue that makes this difficult, I don't know.

    If you look at the long way of declaring a read only property:

    public int myProperty = 0;
    public int MyProperty
    {
        get { return myProperty; }
    }  
    

    And then look at the disassembled code. The setter is not there at all.

    public int Test2
    {
        get
        {
            return this._test;
        }
    }
    
    public int get_Test2()
    {
        return this._test;
    }
    

    disassembled C# code from IL

提交回复
热议问题