条件 C# 二进制序列化
我正在使用 BinaryFormatter 按条件序列化类及其变量。例如:
[Serializable]
public class Class1
{
private Class2 B;
...
}
[Serializable]
public class Class2{...}
我希望变量 B 仅在远程处理时序列化,但当我将其序列化到文件存储时则不序列化。 问题:
1)我知道在XmlSerialization中我们可以使用[XmlIgnore]和{PropertyName}指定有条件地忽略属性。这是 [NonSerialized] 的等效方法吗?
2)对于具有[Serialized]属性的类,如何在运行时忽略它?
I am using BinaryFormatter to serialize a class and its variables by condition. For example:
[Serializable]
public class Class1
{
private Class2 B;
...
}
[Serializable]
public class Class2{...}
I want the variable B to be serialized only when remoting time, but not when i serialize it to file storage.
Questions:
1) I know that in XmlSerialization we can use [XmlIgnore] and {PropertyName}Specified to ignore the property conditionally. Is that a equivalent method for [NonSerialized]?
2) For a class with [Serializable] attribute, how to ignore it at the runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,我建议您不要使用
BinaryFormatter
。如果有的话,维护也是一件令人头疼的事情。使用 XML 序列化或某种协议缓冲区。ISerializable
, and if you do you will know which serialization context is active (remoting, file etc.)Generally speaking I advise you against using
BinaryFormatter
. It is a maintenance headache if there ever was one. Use XML serialization or some kind of protocol buffers.正如已经提到的,它不存在。您可以编写自己的代码,尽管它有点混乱(也就是说,如果您不想按照已经建议的方式实现 ISerialized 接口)。
<前><代码>[可序列化]
公开课A级
{
[关于序列化]
私有无效OnSerializing(StreamingContext上下文)
{
//根据上下文或一些内部布尔值设置 BSerialized = B
BSerialized = B;
}
[关于序列化]
私有无效OnSerialized(StreamingContext上下文)
{
//清除BSerialized
BSerialized=空;
}
[关于反序列化]
私有无效OnDeserialized(StreamingContext上下文)
{
//从BSerialized恢复B
B=BSerialized;
BSerialized=空;
}
[非序列化]
私人 B 级 B 级;
私有 B 类 B 序列化;
}
[可序列化]
公共类 B 类 { }
你不能忽视它。您只能在运行时更改属性的属性,并且由于 NonSerialized 属性不采用 true / false 参数,因此您无法在运行时对其执行任何操作。
As already mentioned, it doesn't exist. You could code your way out of although it is a bit messy (that is if you don't want to implement the ISerializable interface as already suggested).
You can't ignore it. You can only change properties on attributes at runtime and since the NonSerialized attribute doesn't take a true / false argument, you cannot do anything about it runtime.
我编写了一个相当简单但可扩展的框架来使用绑定解决此类问题。不确定我完全理解,但这是可能的:
http://binaryserializer.codeplex.com
I wrote a rather simple but extensible framework to solve this sort of problem using bindings. Not sure I completely understand but this is possible:
http://binaryserializer.codeplex.com