首页 新闻 会员 周边

如何XML序列化一个接口

0
悬赏园豆:200 [已关闭问题]

看如下代码 如何进行序列化和反序列化,是设计的问题吗?

 

代码
1 class Digit : IGoods
2 {
3 public String name
4 {
5 get
6 { return "Digit"; }
7 }
8
9 public int Power = 220;
10
11 }
12
13 class Book : IGoods
14 {
15 public String name
16 {
17 get
18 { return "Book"; }
19 }
20
21 public String isbn = "123xxx";
22
23 }
24
25 public interface IGoods
26 {
27 String name { get; }
28 }
29
30 public class Shop
31 {
32 public List<IGoods> LGood { get; set; }
33
34 public Shop()
35 {
36 LGood = new List<IGoods>();
37 }
38 public void addtoShop(IGoods lg)
39 {
40 LGood.Add(lg);
41 }
42 }
43
44 static void Main(string[] args)
45 {
46
47
48 Shop shop=new Shop();
49
50 shop.addtoShop( new Book());
51
52 shop.addtoShop(new Digit());
53 XmlSerializer xs1 = new XmlSerializer(typeof(Shop));
54 FileStream fs1 = new FileStream("test.xml", FileMode.Create, FileAccess.Write);
55 xs1.Serialize(fs1, shop);
56 fs1.Close();
57 }

 

tingchina的主页 tingchina | 初学一级 | 园豆:0
提问于:2010-03-09 16:32
< >
分享
其他回答(2)
0

XmlSerializer不支持接口申明,不过这里可以改为抽象类。要么自己控制Class中序列化的方法来进行序列化。

接口只是一个协议,它本身是没有实现方式的,其实例也谈不上序列化出来,关键的还是class本身。

同时你发布的代码没加[Serializable]申明。

西越泽 | 园豆:10775 (专家六级) | 2010-03-09 16:44
重点是从如何序列化一个接口
支持(0) 反对(0) tingchina | 园豆:0 (初学一级) | 2010-03-09 16:57
@tingchina:XmlSerializer不支持接口序列化。
支持(0) 反对(0) 西越泽 | 园豆:10775 (专家六级) | 2010-03-09 17:24
这种需求有什么办法实现? 实现这个逻辑就好
支持(0) 反对(0) tingchina | 园豆:0 (初学一级) | 2010-03-09 17:25
@tingchina:自己去实现序列化吧在Shop中,你可以参考下http://topic.csdn.net/u/20090204/13/692853c5-f84f-43bb-9852-9763e5757378.html
支持(0) 反对(0) 西越泽 | 园豆:10775 (专家六级) | 2010-03-09 17:31
0

序列化和接口没有关系,直接和被序列化的运行时的类型有关,只要你的Book类和Digit类上有[Serializable]就能序列化吧

Gray Zhang | 园豆:17610 (专家六级) | 2010-03-09 17:15
不行..
支持(0) 反对(0) tingchina | 园豆:0 (初学一级) | 2010-03-09 17:26
0

1、需要在Class前加上[Serializable]标签

2、抽象类适合事物的抽象,接口适合动作的规约。Goods作为抽象类更加合适。

3、附上一段关于定义可序列化类的代码片段:

 public enum EntityType { Dict, SysDict, Data };
    [Serializable]
    [XmlType("entity")]
    public class EntityMeta
    {
        private EntityType _type = EntityType.Data;
        private string _primaryKey = "UID";

        [XmlAttribute("name")]
        public string Name { get; set; }
        [XmlAttribute("caption")]
        public string Caption { get; set; }
        [DefaultValue("UID")]
        [XmlAttribute("primaryKey")]
        public string PrimaryKey
        {
            get
            {
                return _primaryKey;
            }
            set
            {
                _primaryKey = value;
            }
        }   
        [XmlArray("properties")]
        public PropertyMetaCollection PropertyMetaSet { get; set; }

查尔斯 | 园豆:3832 (老鸟四级) | 2010-03-09 17:25
恩 改成抽象类视乎也没法序列化,假设 IGoods 是抽象类 但是我实际放入的是一个派生类 序列器怎么检查?
支持(0) 反对(0) tingchina | 园豆:0 (初学一级) | 2010-03-09 17:29
@tingchina: public List<IGoods> LGood { get; set; }是这里的问题吧,现在报什么错?你把这个List去掉试试看,或者照我给你的代码加上XmlArray
支持(0) 反对(0) 查尔斯 | 园豆:3832 (老鸟四级) | 2010-03-09 17:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册