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

前端 未结 9 2395
傲寒
傲寒 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 11:13

    I've seen this used with the design:

    public class whatever
    {
        public string WhateverId { get; private set; }
    
        public static whatever Create(string whateverId)
        {
            return new whatever() { WhateverId = whateverId };
        }
    }
    

    So you create whatever class, but after it's created the id can't be changed because it might break things that are connected to it.

    the private set just gives the simple initializer syntax, I kind of like it for some scenarios.

    Also can be used if it's changeable, but you need to manage it when changes are made

    public void SetWhateverId(string whateverId)
    {
        DisconnectAllCurrentWhateverIdReferences();
        WhateverId = whateverId;
        ReconnectAllPreviousWhateverIdReferences();
    }
    

提交回复
热议问题