Private 'set' in C# - having trouble wrapping my brain around it

前端 未结 9 2399
傲寒
傲寒 2021-02-12 10:34

I\'ve seen a lot of example code written using something like (please forgive how horribly canned this is):

public class Test
{
   public object Thingy { get; pr         


        
9条回答
  •  鱼传尺愫
    2021-02-12 10:57

    Basically, it is a readonly property. If it was written in full (not as an auto property) you would simply leave out the setter.

    Two examples that are largely the same:

    class Foo1
    {
       public int Id { get; private set; }
       public Foo1()
       {
           Id = lastId ++;
       }
    }
    
    class Foo2
    {
       private int _id;  // could be readonly 
       public int Id { get { return _id; } }
       public Foo2()
       {
           _id = lastId ++;
       }
    }
    

提交回复
热议问题