InvalidOperationException when trying to assign an XmlElementAttribute to a custom IXmlSerializable object under .NET CF

StackOverflow https://stackoverflow.com/questions/12164716

Question

Let's assume we have some code similar to this:

[XmlRoot("class-a")]
public class ClassA
{
    [XmlElement("variable")] // without this everything works fine
    public ClassB<Type1, Type2> Variable;

    public ClassA()
    {
        new XmlSerializer(typeof(ClassA)); // exception occurs here
    }
}

public class ClassB<TKey, TValue>
    : NonSerializableClassC<TKey, TValue>, IXmlSerializable
{
    // irrelevant stuff
}

In the context of the title everything is pretty self-explanatory.

Please note that this is the .NET CF [3.5], where insides of the XmlSerialization are completely different (due to performance issues). The same code works perfectly fine under the desktop version of the .NET [4.0]. Moreover, the problem isn't actually affecting my work, since I use XmlElementAttribute only for element alias, what is easily reachable by renaming the variable itself. But that's not a real solution though.

So... any ideas why isn't this working?


Last entries of the stack-trace:

// . . .
System.Xml.dll!System.Xml.Serialization.XmlSerializer.XmlSerializer(System.Type type = {Name = "ClassA" FullName = "RandomProject.ClassA"})
System.Xml.dll!System.Xml.Serialization.XmlSerializer.XmlSerializer(System.Type type = {Name = "ClassA" FullName = "RandomProject.ClassA"}, System.Xml.Serialization.XmlAttributeOverrides overrides = null, System.Type[] extraTypes = null, System.Xml.Serialization.XmlRootAttribute root = null, string defaultNamespace = null)
System.Xml.dll!System.Xml.Serialization.XmlSerializer.findTypeByType(System.Type type = {Name = "ClassA" FullName = "RandomProject.ClassA"}, string defaultNamespace = null)
System.Xml.dll!System.Xml.Serialization.XmlSerializationReflector.FindType(System.Type type = {Name = "ClassA" FullName = "RandomProject.ClassA"}, bool encoded = false, string defaultNamespace = null, bool searchIntrinsics = true)
System.Xml.dll!System.Xml.Serialization.XmlSerializationReflector.AddType(System.Type type = {Name = "ClassA" FullName = "RandomProject.ClassA"}, bool encoded = false, string defaultNS = null, bool genericNullableArg = false)

UPD1: By the way, if I add XmlTypeAttribute/XmlRootAttribute above the ClassB declaration - the same exception occurs, in the same place.

Was it helpful?

Solution

You could try.

public class ClassB<TKey, TValue>
    : NonSerializableClassC<TKey, TValue>, IXmlSerializable
where TKey : IXmlSerializable
where TValue : IXmlSerializable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top