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

后端 未结 3 1934
暖寄归人
暖寄归人 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.

    0 讨论(0)
  • 2021-02-13 16:02

    Since you can't declare Fields in Interfaces, you should not use Public Fields. All fields should be private only.

    If your code depends upon Abstractions, you need to use Interfaces and here the Public Fields are not available.

    0 讨论(0)
  • 2021-02-13 16:09

    The short version is that always using properties instead of public (or, really, even protected) fields has been a fundamental design choice in .NET since the very beginning.

    The slightly longer version is that adding support for public fields would add complexity to the data binding framework (whichever one you're referring to). Fields also lack any kind of support for change notification, which is a fairly important aspect of data binding (at least in a stateful environment like Winforms development). Even at the level of retrieving and setting values, fields and properties are different; while the syntax in VB.NET or C# for retrieving or setting the value of a property is (by design) the same as that of a field, the mechanism used to do this in a programmatic scenario like data binding is different for properties vs. fields.

    In the end, this all just means that it would take more work to add support for public fields to any data binding scenario, so since it's an anti-pattern anyhow this work isn't done.

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