Serialize an IntPtr using XmlSerializer
I'm wondering why the IntPtr type is not supported by the XmlSerializer implementation. When I try to serialize a class including a field of IntPtr type, the serialization fails telling me that IntPtr is not supported, and ignore that member.
To workaround this, I translate the IntPtr value to a Int64... but is it a good idea? It should be, as far I can think. In concrete, I need to serialize a window handle, which is typed IntPtr in .NET framework. Am I do开发者_开发百科ing correct?
The reason that an IntPtr is not serializable is that it generally doesn't make any sense at all when you remove it from it's environment.
If you serialize a window handle, it only makes sense if you deserialize it in the same spot, while the window still exists. If you deserialize it on a different computer, in a different application, or after the window is removed, the handle has no meaning.
So, you can cast it to a type that is serializable, but it's up to you to make sure that it still makes sense when you deserialize it.
Think of IntPtr as void*. If you want to do anything useful with it, you have no choice but to cast it to something else.
So yes, casting it to int64 in order to serialize it is perfectly reasonable.
精彩评论