Automated property with getter only, can be set, why?

前端 未结 6 2122
暗喜
暗喜 2020-12-02 16:27

I created an automated property:

public int Foo { get; } 

This is getter only. But when I build a constructor, I can change the value:

6条回答
  •  日久生厌
    2020-12-02 16:59

    Auto property feature was added to the language during C# 3.0 release. It allows you to define a property without any backing field, however you still need to use constructor to initialize these auto properties to non-default value. C# 6.0 introduces a new feature called auto property initializer which allows you to initialize these properties without a constructor like Below:

    Previously, a constructor is required if you want to create objects using an auto-property and initialize an auto-property to a non-default value like below:

    public class MyClass
    {
        public int Foo { get; }
    
        public Foo(int foo)
        {
            Foo = foo;
        }
    }
    

    Now in C# 6.0, the ability to use an initializer with the auto-property means no explicit constructor code is required.

    public string Foo { get; } = "SomeString";
    
    public List Genres { get; } = new List { "Comedy", "Drama" };
    

    You can find more information on this here

提交回复
热议问题