开发者

Is there any way to xml serialize an anonymous type in .net using C#

开发者 https://www.devze.com 2023-01-11 23:24 出处:网络
Is there an开发者_Python百科y way to serialize an anonymous type in .net? Normal XmlSerializer fails because the type has no parameterless constructor defined; and NetDataContractSeralizer fails becua

Is there an开发者_Python百科y way to serialize an anonymous type in .net? Normal XmlSerializer fails because the type has no parameterless constructor defined; and NetDataContractSeralizer fails becuase we can't tag DataContract or Serializable attribute to anonymous class.

So is there any clever way around or we just can't do it?


Yes it is possible to serialize an anonymous type. The easiest way that comes to mind is to create a wrapper object which implements ISerializable and uses reflection to inspect an anonymous type for it's fields and serialize them as appropriate. It would be very ugly but would work.

However I think the more important question is

Is it possible to deserialize an anonymous type?

The answer to that is "Not in a general sense". Anonymous types are assembly specific types. So while it's possible to do in a specific manner for a specific anonymous type, it is not doable in the general sense and not between different assemblies since they are internal.


Define "serialize." Serialization implies the ability to deserialize later, and if there is no defined class, there would be nothing to deserialize to. However, if you simply want the data to be placed in an XML file for retreival later, you could certainly do that.

Create an instance of your XML Document of choice (XmlDocument, XDocumnet, whatever) and build it that way (inserting your nodes and values as you go), then use basic File IO to save it somewhere. Or, if you're just trying to pass it between processes or somesuch, pass it as a MemoryStream or Byte[]


Only in a very general sense, in that there is nothing to stop you creating XML that represents an object and nothing to stop you creating an object whose state reflects some XML.

In the specific sense of directly supported by the framework, and resulting in an object of a type defined by an assembly, then no. By definition, an anonymous object isn't defined, that's what makes it anonymous.

0

精彩评论

暂无评论...
验证码 换一张
取 消