C#序列化问题
...我要补充一点,我是用C#相对小白,所以请简单来说:)C#序列化问题
无论如何解释,我有这个类(截断清晰度):
[Serializable]
public class Player : Ship {
和船舶看起来像这样(再次截断):
[Serializable]
public class Ship : TiledActor {
public float MaxUserTurnPerSecond;
public float RemainingShieldStrength;
public float MaxShieldStrength;
public float ShieldRechargeRate;
public float ShieldRechargeDelay;
public Color ShieldColor;
public float ThrusterAccelerationScale;
public Color RippleTrailColor;
public float MinimumRippleSpeed;
public float MaxEnergy;
public float CurrentEnergy;
public float EnergyRechargeRate;
public float MaxSecondaryAmmoCapacity;
public int CurrentSecondaryAmmoCount;
public Weapon PrimaryWeapon;
public Weapon SecondaryWeapon;
protected ShieldActor ShieldTex;
[NonSerialized]
public MoXNA.ParticleMachines.PM_Explosion_Particle_Count ExplosionSize;
[NonSerialized]
protected MoXNA.ParticleMachines.MinSpeedRippleTrail rippleTrail;
/* ... Truncated here */
所以,你可以看到,我想序列化的播放器类。然而,当我试试这个,我得到这个错误:
An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
Additional information: Type 'MoXNA.ParticleMachines.MinSpeedRippleTrail' in Assembly 'SpaceshipInABox, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
这里奇怪的是,我打上rippleTrail(这是MinSpeedRippleTrail对象)为[非序列化] ...我不想要序列化它(这只是一个视觉效果)。
我使用了“查找所有引用”,并且这是唯一的MinSpeedRippleTrail对象在整个程序中,那该死什么?
谢谢。
如果您使用的是XML序列化,则可以使用XmlIgnoreAttribute,否则将rippleTrail成员更改为方法。例如:GetRippleTrail()
他明确表示他使用**二进制**序列化.. – BrokenGlass 2011-02-25 18:09:43
仍然不像他的问题的解决方案。 – 2011-02-25 18:10:53
是的,我误解了它。我不会更新我的答案,也许有人会面对与XML序列化相同的问题:) – Davita 2011-02-25 18:11:21
这里通常的问题是一个事件。 BinaryFormatter包含许多人不期望的事件。本次活动现场必须标明记号,例如:
[field:NonSerialized]
public event EventHandler Foo;
这是痛苦容易得到事件订阅,你没有预料打破串行器(捕获类,也许)。
不过,我也鼓励你:
- 不使用公共领域;使用属性
- 不使用BinaryFormatter - 它最终咬人大多数人;并且难以咬住
如果你想要一个与XNA一起工作的二进制串行器,请考虑protobuf-net;它速度更快,产量更小,适应变化更加优雅......并且是免费的。警告:我写了。
你可以显示代码引发此错误的位置吗?你试图写哪些数据,哪些不是。 – Spidy 2011-02-25 18:11:19
类型:Color,Weapon,ShieldActor是否可串行化? – Maciek 2011-02-25 18:13:26
我不明白为什么这不起作用,但您可以尝试以下方法。尝试向'MinSpeedRippleTrail'类/结构中添加'Serializable',或许尽管应用了NonSerialized属性,它仍然首先检查它是否可以被序列化? – 2011-02-25 18:14:14