序列化:无法将类型 string[][] 转换为 string[]

Serialization: Cannot convert type string[][] to string[]

我有一个带有锯齿状数组的 class。当我尝试序列化它时,出现以下异常:

System.InvalidOperationException HResult=0x80131509 Message=Unable to generate a temporary class (result=1). error CS0030: Cannot convert type 'string[][]' to 'string[]' error CS0029: Cannot implicitly convert type 'string[]' to 'string[][]'

重现问题的简单程序:

using System.IO;
using System.Xml.Serialization;

namespace JaggedArraySerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Class1));
            var class1 = new Class1();
            using (TextWriter stream = new StreamWriter(@"C:\temp\test.xml"))
            { 
                xmlSerializer.Serialize(stream, class1);
            }
        }
    }
}

和class类1

using System;
using System.Xml.Serialization;

namespace JaggedArraySerialization
{
    [Serializable]
    public class Class1
    {
        [XmlElement]
        public string[][] MyJaggedArray { get; set; }
    }
}

如何序列化锯齿状数组?

您可以在 属性 MyJaggedArray 上指定类型,如下所示:

    [Serializable]
    public class Class1
    {
        [XmlElement(Type = typeof(string[][]))]
        public string[][] MyJaggedArray { get; set; }
    }