c# private set

A private setter is useful if you have a read only property and don't want to explicitly declare the backing variable.

So:

public int MyProperty
{
    get; private set;
}


is the same as:

private int myProperty;
public int MyProperty
{
    get { return myProperty; }
}


For non auto implemented properties it gives you a consistent way of setting the property fromwithin your class so that if you need validation etc. you only have it one place.

To answer your final question the MSDN has this to say on private setters:

However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, it is recommended to make the objects immutable by declaring the set accessor as private.


http://stackoverflow.com/questions/3847832/understanding-private-setters

你可能感兴趣的:(c#)