Tôi muốn sắp xếp từng đối tượng. Tôi đã có cấu trúc này cơ bản lớp:C# Nối tiếp các lớp lồng nhau
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);
}
}
}
}
Lớp Clock được định nghĩa như thế này:
[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);
}
}
Các ClockProperties cơ bản:
[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);
}
}
}
}
Khi tôi cố gắng sắp đặt từng đối tượng Clock
với mảng bao gồm ClockProperties
, tôi nhận được ngoại lệ là Controller
không được đánh dấu nối tiếp. Thành thật mà nói, tôi không hiểu tại sao. Tôi cho rằng tôi chỉ tuần tự hóa đối tượng Clock
và do đó chỉ đánh dấu lớp đó và ClockProperties
là Serializable
. Tui bỏ lỡ điều gì vậy?
Cảm ơn bạn, tôi đã cố gắng '[NonSerialized]', như tôi stumbled khi nó. Không biết về cú pháp đó '[field: NonSerialized]'. Nó hoạt động như dự định. – rdoubleui
Đẹp, không biết về điều đó. – Svish