c# private set

来源:互联网 发布:北京高瓴投资大数据 编辑:程序博客网 时间:2024/06/04 21:34

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

0 0
原创粉丝点击