How to Access Object Binaries in .NET 4?
I need to read objects binary data (i开发者_如何学编程ncluding private fields) to process and serialize them in a specific way.
How can I do this in C#, do I need MSIL coding?
You can do it using reflection and (optionally) dynamic IL generation.
For example, once you know the type (i.e. have a System.Type
instance), you can enumerate all fields (type.GetFields()
returns a list of FieldInfo
objects), and then use GetValue
method to get field value. This works with private fields, as long as the security trust level checks are passed.
This is not very fast, so you may want to precompile the field access code (only do that after the profiler tells you!). In this case, you can use System.Reflection.Emit
and DynamicMethod
facilities. (you can find the tutorials on Google and on MSDN; I found it helpful to compile some functions that do what I have to do with C#/F# and then inspect the MSIL output in Reflector/ildasm).
Actually it's quite easy. If you just want to read binary data (not serialized objects, but raw binary data), you can use BinaryReader
.
Start by implementing ISerializable. That interface allows you to control serialization manually: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx
精彩评论