XmlSerializer的:"类型'类型'可以在此上下文中QUOT使用; [英] XmlSerializer: "The type 'Type' may not be used in this context"

查看:206
本文介绍了XmlSerializer的:"类型'类型'可以在此上下文中QUOT使用;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何使用的的XmlSerializer 的,在不使用的 XmlInclude 的属性序列化任何类。一般的作品,但与下面的代码我得到一个异常:

I'm trying to figure out how to serialize any class using the XmlSerializer, without using the XmlInclude attribute. Generally works, but with the following code I get an exception:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace Test
{
    public class ReactObject { }

    public class ReactListObject : ReactObject { }

    public class ReactList<T> : ReactObject, ICollection, IList<T>
    {
        public ReactList() { }

        public virtual void AddRange(IEnumerable<T> values) { }

        [XmlArray(ElementName = "Items", IsNullable = false)]
        public T[] Items
        {
            get { lock (SyncRoot) { return (ItemsList.ToArray()); } }
            set { lock (SyncRoot) { ItemsList = new List<T>(value); } }
        }

        protected List<T> ItemsList = new List<T>();

        public bool IsSynchronized { get { return (true); } }
        public object SyncRoot { get { return (mRootObject); } }

        private object mRootObject = new object();

        public void CopyTo(Array array, int index) { CopyTo(array, index); }

        [XmlIgnore()]
        public T this[int index] {
            get { return (ItemsList[index]); }
            set { ItemsList[index] = value; }
        }

        public int IndexOf(T item) { return (ItemsList.IndexOf(item)); }

        public virtual void Insert(int index, T item) { }

        public virtual void RemoveAt(int index) { }

        public int Count { get { lock (SyncRoot) { return (ItemsList.Count); } } }

        public bool IsReadOnly { get { return (false); } }

        public virtual void Add(T item) { ItemsList.Add(item); }

        public void Clear() { }

        public bool Contains(T item) { return (false); }

        public virtual void CopyTo(T[] array, int arrayIndex) { }

        public virtual bool Remove(T item) { return (false); }

        public IEnumerator<T> GetEnumerator() { return (ItemsList.GetEnumerator()); }

        IEnumerator IEnumerable.GetEnumerator() { return (ItemsList.GetEnumerator()); }
    }

    [XmlInclude(typeof(B))]
    public class A : ReactListObject
    {
        public int AValue = 1;
    }

    public class B : A
    {
        public int BValue = 2;
    }

    public class AList : ReactList<A>
    {

    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            // NOT good serializer for the type AList
            XmlSerializer ser1 = new XmlSerializer(typeof(ReactObject), new Type[] { typeof(A), typeof(B), typeof(ReactList<A>), typeof(AList) });
            // Good serializer for the type AList
            XmlSerializer ser2 = new XmlSerializer(typeof(ReactList<A>), new Type[] { typeof(A), typeof(B), typeof(AList) });
            AList list = new AList();

            list.Add(new A());
            list.Add(new B());

            using (FileStream mStream = new FileStream("C:\\Test.xml", FileMode.Create)) {
                ser2.Serialize(mStream, list);
            }
            using (FileStream mStream = new FileStream("C:\\Test.xml", FileMode.Create)) {
                ser1.Serialize(mStream, list);
            }
        }
    }
}



例外掷是

The exception throw is

类型Test.AList可能无法在此上下文中使用

The type Test.AList may not be used in this context

下面是类图,以帮助读码


Here is the class diagram, to aid the code reading

我想花有关的目标我更多的单词M努力实现:我希望尽量减少XML序列化实例(实际上每种类型的序列化有它自己的序列化的建立;应用程序将重新创建的唯一存在的串行每一个不包括类型应编号的时间(*)。

I'd like to spend more words about the goal I'm trying to achieve: I want to minimize the creation of XML serializers instances (actually each type serialized has its own serializer; the application would re-create the only existent serializer each time a not-included type shall be serialized. (*)

看来,恕我直言,


  • 这是可能的系列化任何的 ReactObject 的(和派生类型)与类型的序列化的 ReactObject 的,直到一个泛型类中派生层次介绍。额外的类型序列化应覆盖所有预期的类型。

  • 在的情况下从的泛型类的基础上派生的类型的 ReactObject 的,类型不能与类型的序列化进行序列化的 ReactObject 的,但与一般类型的序列化。

  • It's possible to serialize any ReactObject (and derived types) with a serializer of type ReactObject, till a generic class is introduced in the derivation hierarchy. The extra types of the serializer shall cover all expected types.
  • In the case a type derived from a generic class based on ReactObject, the type cannot be serialized with a serializer of type ReactObject, but with a serializer of the generic type.

这可能是一个问题,因为我知道序列化对象的类型,当我需要反序列化。相反,反序列化非一般的 ReactObject 的类型是足够用型普通串行的 ReactObject 的,不知道序列化对象的确切类型。

This could be a problem, since I have to know the type of the serialized object when I need to deserialize it. Instead, to deserialize a "non-generic" ReactObject type is sufficient to use the common serializer of type ReactObject, without knowing the exact type of the serialized object.

(*)其实我不知道这个目标会带来合理的改进。核心问题将是更好的是它为所有(包括)类型单一序列化程序集,或者为每种类型的串行器组装?

(*) Actually I don't know this goal would bring sensible improvements. The core question would be "Is it better a single serializer assembly for all (included) types, or a serializer assembly for each type?"

推荐答案

序列化方很容易 - 而不是使用typeof运算(ReactObject)获取序列化时,使用list.GetType(),它会返回ALIST而非ReactObject和创建正确的串行器。如果你担心实例太多的串行你总是可以让他们在按类型键入一个字典

The serialization side is easy - instead of using typeof(ReactObject) when getting the serializer, use list.GetType(), which will return AList rather than ReactObject and create the correct serializer. If you are worried about instantiating too many serializers you can always keep them in a dictionary keyed by type.

反序列化是更难,因为你必须知道对象的类型第一 - 如果你不能让来电者告诉你会发生什么类型,您将需要读取数据时,你试图反序列化,以确定类型之前。

Deserialization is harder as you have to know the type of object first - if you can't get the caller to tell you what type to expect, you will need to read the data before you try deserializing to determine the type.

这篇关于XmlSerializer的:&QUOT;类型'类型'可以在此上下文中QUOT使用;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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