Why to access a value in an anonymous types, a compiler creates a getter method? Would not it be easier to give a direct access to read-only backing field?

有帮助吗?

解决方案

Because properties of anonymous types are readonly after construction. You cannot change them once the object has been created.

They can achieve this using a get only property, but not with a public field (you can always change a field).


EDIT: I've looked around but couldn't find an obvious reason as to why they didn't go with public read-only fields. However, my best guess is: so that you can have properties.

If they had exposed public fields, and didn't have any properties, inevitably, anonymous types would be unusable by things that look for public properties, e.g. WPF binding. So having properties with private readonly backing fields probably was the safer choice.

其他提示

It's not obvious why they don't simply use a read-only property, but a good reason is this:

If they just used a read-only property, you would know its name and therefore it would be easy to use reflection to change it.

Because they generate a private backing field, it's much harder to know what the name of it is (you'd have to inspect the generated IL), and therefore you are much less likely to change it using reflection. You still could, of course - but it would be such an obviously weird thing to do that you are definitely going to think once or twice before doing so.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top