我有一个专门的类,BusinessObjectList,带有这个声明:
public class BusinessObjectList<T> : List<BusinessObject> where T: BusinessObject {}
我想序列化这个类的对象,比如:
info.AddValue("myList", myList);
我尝试添加ISerializable接口,但没有成功。
public class BusinessObjectList<T> : List<BusinessObject>, ISerializable where T: BusinessObject {}
反序列化时,列表始终为null。 我认为List&lt;&gt;对象是可序列化的,但它们的子类呢?
编辑:
仅供将来参考,以下是整个班级:
BusinessObjectList.cs(当您调用save()时,它会自动在DB上保留所有插入并从列表中删除,并将所有修改后的值保存在业务对象上):
[Serializable()]
public class BusinessObjectList<T> : List<BusinessObject>,ISerializable where T: BusinessObject
{
public delegate void BusinessObjectListDeleteHandler(T objDeleted);
public event BusinessObjectListDeleteHandler deleteHandler;
List<BusinessObject> objsForDelete = new List<BusinessObject>();
public BusinessObjectList()
{
}
public new void Add(BusinessObject item)
{
base.Add(item);
}
public new T this[int index]
{
get
{
return (T)base[index];
}
}
public bool save()
{
foreach (T obj in objsForDelete)
{
if (deleteHandler != null)
deleteHandler(obj);
obj.delete();
}
objsForDelete.Clear();
foreach (BusinessObject obj in this)
{
obj.save();
}
return true;
}
public new void Clear()
{
foreach (BusinessObject obj in this)
{
//obj.delete();
objsForDelete.Add(obj);
}
base.Clear();
}
public new void Remove(BusinessObject obj)
{
// obj.delete();
objsForDelete.Add(obj);
base.Remove(obj);
}
public new void RemoveAt(int index)
{
objsForDelete.Add(this[index]);
base.RemoveAt(index);
}
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// should I do something here??
}
#endregion
}
和BusinessObject.cs:
[Serializable()]
public abstract class BusinessObject:ISerializable
{
public abstract bool save();
public abstract bool delete();
public abstract DbTransaction startTransaction();
public abstract void useTransaction(DbTransaction transaction);
public abstract DbTransaction getTransaction();
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// nothing to serialize here
}
#endregion
}
答案 0 :(得分:4)
首先,您应该继承System.Collections.ObjectModel.Collection<T>
,而不是List<BusinessObject>
。从Collection<T>
继承是最好的,这样你就可以通过重写InsertItem,SetItem等来控制对列表的所有更改(甚至是通过IList<T>
进行的更改)。从集合继承可能也更好。 T
的集合而不是BusinessObject
的集合,以便从基类继承的方法和索引器使用正确的类型。
要回答您的问题,.Net集合类型(包括Collection<T>
)都不可序列化。您需要自己序列化和反序列化集合;有关说明,请参阅here。