我应该如何序列化接口列表? [英] How should I serialize a list of interfaces?

查看:78
本文介绍了我应该如何序列化接口列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何序列化要保存到文件或通过LAN发送的操作列表(即List<iAction> toDo;)?我本打算使用XmlSerializer,但是我更改了列表以包含多种类型的操作,现在我的计划不再起作用了.

是否应该向iAction添加方法,例如iAction.序列化并序列化每个动作而不是整个列表,还是我需要提出其他建议?顺便说一句,我正在使用XmlSerializer,因为我出于其他原因希望将列表保存到XML文件.

这是我正在做的事情(简体):

How should I serialize a list of actions (ie. List<iAction> toDo;) for saving to a file or sending over a LAN? I was going to use XmlSerializer, but I changed my List to include more than one type of action and now my plan doesn''t work anymore.

Should I add a method to iAction such as iAction.Serialize and serialize each action instead of the whole list, or do I need to come up with something else? Btw, I''m using XmlSerializer because I want to save the list to an XML file for other reasons.

Here is what I was doing (simplified):

enum Shape { line, circle, square }

class Action
{
    Point start;
    Point stop;
    Shape drawShape;

    void Draw(Graphics gfx)
    {
        switch(drawShape)
            // gfx.DrawLine / gfx.DrawElipse / gfx.DrawRectangle
    }
}

void Main()
{
    List<Action> toDo;
    toDo.Add(Action);
    toDo.Add(Action);
    toDo.Add(Action);

    XmlSerializer.Serialize(saveFile, toDo);
}



现在,我有一个动作界面以及从中继承的不同动作:



Now I have an action interface and different actions inheriting from it:

interface iAction
{
    void Start(Point start);
    void onMove(Point movedTo);
    void Stop(Point stop);
    void Draw(Graphics gfx);
}

class Line : iAction { ... }
class Path : iAction { ... }
class Square : iAction { ... }
...

void Main()
{
    List<iAction> toDo;
    toDo.Add(Line);
    toDo.Add(Circle);
    toDo.Add(Square);

    XmlSerializer.Serialize(saveFile, toDo); // "Error: Can not serialize interface iAction."

}

推荐答案

您需要使用SerializableAttribute和其他提示.在此处查看[ ^ ]
You need to use the SerializableAttribute and other hints. Have a look here[^]


这篇关于我应该如何序列化接口列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆