简体   繁体   中英

XML Serialization and List<enum> c#

I am trying to serialise a List<> of enums with the XMLSerializer when I get the following Error :

'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. 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. 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. Serializers cannot work of interfaces, you need to provide them with a concrete type.

Can you use this typeof(List<EnumType>) instead ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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