gpt4 book ai didi

C# 嵌套类的序列化

转载 作者:太空狗 更新时间:2023-10-29 21:15:41 26 4
gpt4 key购买 nike

我想序列化一个对象。我有这个基本的类结构:

class Controller
{
Clock clock;

public event EventHandler<ClockChangedEventArgs> ClockChanged;

public void serializeProperties()
{
using (FileStream stream = new FileStream(PROPERTIES_FILE, FileMode.Append, FileAccess.Write, FileShare.Write))
{
IFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(stream, clock);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}

public void deserializeProperties()
{
using (FileStream stream = new FileStream(PROPERTIES_FILE, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
{
IFormatter formatter = new BinaryFormatter();
try
{
clock = (Clock)formatter.Deserialize(stream);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
clock = new Clock();
}
finally
{
clock.ClockChanged += new EventHandler<ClockChangedEventArgs>(clock_ClockChanged);
}
}
}
}

时钟类定义如下:

[Serializable]
public class Clock
{
ClockProperties[] properties;
int current;
bool isAnimated;

public event EventHandler<ClockChangedEventArgs> ClockChanged;

public Clock()
{
properties = new ClockProperties[2];
properties[0] = new ClockProperties("t1");
properties[1] = new ClockProperties("t2");
properties[0].ValueChanged += new EventHandler(Clock_ValueChanged);
properties[1].ValueChanged += new EventHandler(Clock_ValueChanged);
}
}

底层时钟属性:

[Serializable]
public class ClockProperties
{
public event EventHandler ValueChanged;

int posX, posY;
string clock;

public ClockProperties(string name)
{
clock = name;
}

public void OnValueChanged(EventArgs e)
{
if (ValueChanged != null)
{
ValueChanged(this, e);
}
}

public string Clock
{
get { return clock; }
set {
if (!value.Equals(clock))
{
clock = value;
OnValueChanged(EventArgs.Empty);
}
}
}

public int PosX
{
get { return posX; }
set {
if (!(value == posX))
{
posX = value;
OnValueChanged(EventArgs.Empty);
}
}
}

public int PosY
{
get { return posY; }
set {
if (!(value == posY))
{
posY = value;
OnValueChanged(EventArgs.Empty);
}
}
}


}

当我尝试使用包含的 ClockProperties 数组序列化 Clock 对象时,我得到一个异常,即 Controller 未标记为可序列化.老实说,我不明白为什么。我假设我只序列化了 Clock 对象,因此只将该类和 ClockProperties 标记为 Serializable。我错过了什么吗?

最佳答案

在 Clock 类中标记 ClockChangedEvent [field:NonSerialized]

关于C# 嵌套类的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1900893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com