问题
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 possible to use public fields for data binding or even for JSON serializers like JavaScriptSerializer class.
Is there any good reason to ignore public fields in these cases? Or is it just some kind of convention? Or just to force users to use properties?
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/27582340/why-cant-we-use-public-fields-for-data-binding-in-c