简体   繁体   English

XML序列化和列表 <enum> C#

[英]XML Serialization and List<enum> c#

I am trying to serialise a List<> of enums with the XMLSerializer when I get the following Error : 当出现以下错误时,我正在尝试使用XMLSerializer序列化枚举的List<>

'GameDataBuilder.vshost.exe' (Managed): Loaded 'uoqssn9i'
A first chance exception of type 'System.NullReferenceException' occurred in uoqssn9i
A first chance exception of type 'System.TypeInitializationException' occurred in uoqssn9i
A first chance exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll

I have taken a look inside the List<> and all of the values are valid. 我在List<>进行了查看,所有值均有效。 Using the same code I can serialize an enum (not list) and all other types (int, float etc) and Lists of those other types just fine. 使用相同的代码,我可以序列化一个枚举(不是列表)和所有其他类型(int,float等),而这些其他类型的列表也可以。 It just seems like the list of enum causes errors. 似乎枚举列表会导致错误。

Anyone came across this problem before? 有人遇到过这个问题吗?

Any help would be much appreciated 任何帮助将非常感激

edit : 编辑

Serialize Method: 序列化方法:

public void SerialiseToXML(XmlSerializer serializer, string directory)
{

    string fileName = directory + m_Name + ".xml";

    if (!Directory.Exists(directory))
    {
        DirectoryInfo di = Directory.CreateDirectory(directory);
    }

    if (!File.Exists(fileName))
    {
        using(File.Create(fileName))
        {
        }
    }

    using (TextWriter textWriter = new StreamWriter(fileName))
    {
        serializer.Serialize(textWriter, m_Objects);
    }
}

Serializer: 序列化器:

private void GenerateSerializer()
{
    List<Type> dynamiclyCreatedTypes = mTypeManager.GetSerializeableTypes();
    m_Serializer = new XmlSerializer(typeof(List<ISerializeable>), dynamiclyCreatedTypes.ToArray());
}

The List Is Generated like this: 该列表是这样生成的:

type = typeof(List<>).MakeGenericType(type);

I think the problem is that you are using typeof(List<ISerializeable>) to create the XmlSerializer. 我认为问题在于您正在使用typeof(List<ISerializeable>)创建XmlSerializer。 Serializers cannot work of interfaces, you need to provide them with a concrete type. 序列化程序无法使用接口,您需要为其提供具体的类型。

Can you use this typeof(List<EnumType>) instead ? 您可以改用此typeof(List<EnumType>)吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM