C#类序列化 [英] C# Class Serialization

查看:86
本文介绍了C#类序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,



我有一个问题,但我很确定答案是肯定的。但是可以在序列化期间更改属性的类型。



例如:



如果你有一个bool属性,但你想将它保存为xml文件中的字符串(为了便于阅读)。这可能吗?



我还没有制作任何示例代码,因为它现在只是一种理论方法。我已经做了一些谷歌搜索,但我没有找到任何结果,说它是/不可能所以我想我会问。

Hey guys,

I''ve got a question, but I''m pretty sure the answer is no. But is it possible to change the type of a property during serialization.

For example:

If you have a bool property but you wanted to save it as a string in an xml file (for readability purposes). Is this possible?

I''ve not produced any sample code yet as it is just a theoretical approach at this time. I''ve done some googling but I''ve not found any results that say it is/isn''t possible so I thought I would ask.

推荐答案

你对不非常正确,但这与序列化无关。 您无法在运行时更改类型声明。这一事实比序列化更为基础。我不知道你为什么要这样做(这就是为什么建议你告诉我们你的最终目标);我认为整个想法都是基于一些误解。



严格地说,你可以随时改变属性的类型:如果声明了(编译时)属性的类型是一些具有后代类的类,属性的运行时类型可以是这些后代类中的一个或另一个。这是OOP的一般原则。然而,这方面是微不足道的;我相信你明白了无论如何,除了赋值兼容性之外,你不能将布尔值更改为字符串或类似的东西。



-SA
You are pretty much right about "no", but this is not really related to serialization. You cannot change the declaration of a type during run-time. This fact is more fundamental than serialization. I don''t know why would you want it (that''s why you are advised to tell us your ultimate goals); I think the whole idea is based on some misconception.

Strictly speaking, you can always change the type of the property in certain sense: if the declared (compile-time) type of the property is some class which has descendant classes, the run-time type of the property could be one or another of those descendant classes. This is a general principle of OOP. However, this aspect is trivial; and I''m sure you understand it. Anyway, you cannot change Boolean to string, or anything like that, anything beyond assignment compatibility.

—SA


布尔值被序列化为false或true - 这是你要改变的吗? - 它不起作用。

如果你想更改属性的名称,你可以使用 XmlElementAttribute

A boolean value is serialised to "false" or "true" - is it this what you want to change? - It does not work.
If you want to change the name of the property, you can use the XmlElementAttribute:
[System.Xml.Serialization.XmlElementAttribute("This_is_the_text_you_want_to_show")]
public bool MyIncomprehensibleProperty
{ ... }


原则上,您可能总是编写自己的序列化内容(请注意:为所有但非常简单的情况编写可靠的序列化工具是一项非常困难的任务):最多序列化的重要属性是可逆性:如果序列化一个对象,那么你必须确保你可以恢复它。如果您的序列化代码保证可逆性,它可以以您喜欢的形式存储对象状态(您更喜欢)。
In principle, you may always write you own serialization stuff (please note: writing a reliable serialization facility for all but very simple cases it is a quite difficult task): the most important property of serialization is reversibility: if you serialize an object then you have to be sure you can get it back to life. Provided your serialization code warrants reversibility, it can store object state in the form it likes (you like) more.


这篇关于C#类序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆