Auto-Implemented Properties c#

后端 未结 5 471
小鲜肉
小鲜肉 2020-12-01 21:40
  1. could someone explain me what\'s the idea behind using Auto-Implemented Properties c#?

    public class Customer
    {
        public int ID { get; set; }
        p         
    
    
            
5条回答
  •  情书的邮戳
    2020-12-01 22:20

    Automatically implemented properties are essentially syntactic sugar. Once compiled, the backing store exists. It just isn't available from the source code.

    As others have stated, properties and fields are not equivalent. Fields and properties aren't compatible so changing between them is a breaking change. In addition, you cannot use data binding with fields.

    Final point. Though in your case there's little functional difference between the example and a public field, you can change the visibility of one of the accessors. So, to create a read-only property using an automatic property, you may do something like:

    public int ID { get; private set; }
    

    In this case, the get accessor is public, as per the entire signature, but the set accessor is private.

提交回复
热议问题