从基类派生的类中使用XmlSerializer构造函数出错

7
以下代码指定了一个类型"MyBase64Binary",该类型派生自基类"TestBase"。
using System;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;

namespace Test
{
    public class TestBase
    {
        public TestBase()
        {
        }
    }

    [XmlType(TypeName = "base64Binary"), Serializable]
    public partial class MyBase64Binary : TestBase
    {
        [System.Xml.Serialization.XmlTextAttribute(DataType = "base64Binary")]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public Byte[] __Value;

        [XmlIgnore]
        public Byte[] Value
        { 
            get { return __Value; }
            set { __Value = value; }
        }

        public MyBase64Binary()
        {
        }

    }
}

如果我尝试像这样创建一个XmlSerializer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer s = new XmlSerializer(typeof(Test.MyBase64Binary));
        }
    }
}

从这里开始,我得到一个InvalidOperationException错误:

{"There was an error reflecting type 'Test.MyBase64Binary'."}

内部异常告诉我以下信息:

{"Cannot serialize object of type 'Test.MyBase64Binary'. Consider changing type of XmlText member 'Test.MyBase64Binary.__Value' from System.Byte[] to string or string array."}

如果我不派生自“TestBase”类,那么一切都很好。我找不到解决方案。请帮忙。出了什么问题?来自德国的问候。Jan
2个回答

4
如果你将XmlTextAttribute更改为XmlAttribute或XmlElement,那么应该就没问题了。由于你试图使用XmlTextAttribute,它假定它是某种字符串。如果你想要序列化一个实际的字节数组,请尝试使用XmlAttribute或XmlElement。

1
+1,问题在于属性,与基类无关。 - Hans Passant
2
谢谢!似乎可以工作!但是如果省略基类并且不派生,序列化器为什么会起作用呢?难道异常也不应该发生吗? - Jan Ryll
@Jan 遇到了同样的问题。如果省略基类,它就能正常工作。这种行为有点奇怪... - Sven

-1

在你的基类中添加[Serializable]有帮助吗?我建议你确保你的基类也被正确地装饰了。虽然我不知道这是否有帮助。


3
XmlSerializer 不使用 SerializableAttribute - Venemo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接