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

前端 未结 9 2417
傲寒
傲寒 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:12

    As a simple example; it is a cheap way of making an "immutable enough" object (for use in threading, state, etc). But also anywhere where the client simply shouldn't need to assign it, or can't be trusted to assign it (correctly).

    Another example might be a list:

    public List Items {get;private set;}
    

    since we might call obj.Items.Add() etc, but we would rarely assign obj.Items = .... However, this example is marred by needing explicit initialization in the constructor, and XmlSerializer hates it - to be honest for lists I mainly use:

    private readonly List items = new List();
    public List Items {get { return items;}}
    

    which solves both of these.

    As another example, contrasting:

    private readonly int foo;
    public int Foo {get{return foo;}}
    

    vs

    private readonly int foo;
    public int Foo {get{return foo;} private set {foo=value;}}
    

    this pattern may be useful in serialization, for example with DataContractSerializer (with the addition of some attributes), since many serializers will still look for private accessors. This avoids us having to decorate our internal state (foo), but gives the veneer of privacy to the set.

    Ultimately anything can be bypasses and assigned via reflection, so private set is only intended to avoid accidental damage to data.

提交回复
热议问题