I understand how XMLSerializer could work by using reflection to figure out what public read/write fields or properties it should be using to serialize or de-serialize XML. Yet XMLSerializer requires that the fields be public and read/write.
However, DataContractSerializer is able to read or write to or from completely private fields in a class. So I'm wondering how this is even possible with out explicitly giving DataContractSerializer additional access rights to my class(es).
Reflection has many features. XmlSerializer
has, via "sgen.exe" the ability to pre-build the serialization code to a binary (dll). This is useful in some scenarios that don't allow dynamic code, but dlls (just like your code) are limited to the accessible API.
However... reflection isn't this limited, and with enough access you can do pretty much anything. For performance you probably don't want to be using reflection directly a lot, but if you have enough permissions to create IL directly in memory (DynamicMethod
), then you can tell it (on a per-dynamic-method basis) which Type
the code is associated with. For example, if I create a DynamicMethod
passing typeof(Foo)
as the owner
argument, then that dynamic method has full access to all members (including fields) on Foo
. For info, Delegate.CreateDelegate
provides similar access to otherwise protected data. Since DataContractSerializer
doesn't worry about pre-generation, it can use this access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With