When should use Readonly and Get only properties

前端 未结 5 439
深忆病人
深忆病人 2020-12-02 05:00

In a .NET application when should I use \"ReadOnly\" properties and when should I use just \"Get\". What is the difference between these two.

private readonl         


        
5条回答
  •  情深已故
    2020-12-02 05:16

    readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

    http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

    taken from Mark's example:

    public class Fragrance : IFragrance
    {
        private readonly string name;
    
        public Fragrance(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
    
            this.name = name;
        }
    
        public string Spread()
        {
            return this.name;
        }
    }
    

    in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

提交回复
热议问题