Why can't we use public fields for data binding in C#?

后端 未结 3 1933
暖寄归人
暖寄归人 2021-02-13 15:10

I am aware of the advantages of using properties over fields, like being able to provide additional logic when required in the future.

But I really wonder why it\'s not

3条回答
  •  长情又很酷
    2021-02-13 16:01

    There is no technical reason behind this restriction: it is certainly possible to add public fields to the list of properties, and allow binding to them. In fact, there are APIs in .NET that would pick a property or a public field automatically, based on a name alone. For example, LINQ's Expression has PropertyOrField method that would pick one or the other, based on the type returned by the expression in its first parameter.

    However, leaving fields public exposes you to such an array of potential problems, that the designers of systems dependent on reflection often try to discourage use of public fields by withholding support for them from their system design.

    In addition, in systems that rely on events for binding, using a field would not be possible for technical reasons, because one cannot fire an event on setting a public field.

提交回复
热议问题