When should you use a field rather than a property?

前端 未结 7 1962
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 06:56

Can anyone clearly articulate when you use a field and when to use a property in class design?

Consider:

public string Name;

Or:

相关标签:
7条回答
  • 2020-12-06 07:18

    A property like defined above acts like a getter and setter. The only benefits of using a property is that you can treat it like a variable with access restriction.

    public string Name { get; private set; }
    

    This property can be accessed publicly, but can only be set privately. (You wouldn't want anyone changing your name with out your consent now would you! ;) )

    0 讨论(0)
提交回复
热议问题