Public Fields versus Automatic Properties

前端 未结 12 2104
梦谈多话
梦谈多话 2020-11-21 23:34

We\'re often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside worl

12条回答
  •  逝去的感伤
    2020-11-22 00:06

    In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.

    Properties vs. Public Variables

    • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
    • You can't databind against a variable.
    • Changing a variable to a property is a breaking change. For example:

      TryGetTitle(out book.Title); // requires a variable
      

提交回复
热议问题