Home > Enterprise >  C# - Deserialize an abstract class (The specified type is abstract: name='ValueColorConverter&#
C# - Deserialize an abstract class (The specified type is abstract: name='ValueColorConverter&#

Time:11-04

I'm trying to deserialize an abstract class and am getting an exception with message The specified type is abstract: name='ValueColorConverter', namespace='', at <ValueColorConverter xmlns=''>.

void Main()
{
    // <ValueColorConverter xsi:Type="ValueColorConverter_Band" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
    XElement config = XElement.Parse(@"<ValueColorConverter xsi:Type=""ValueColorConverter_Band"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""/>");

    XmlSerializer xs = new XmlSerializer(typeof(ValueColorConverter));
    var vcc = xs.Deserialize(config.CreateReader()) as ValueColorConverter;
}

[Serializable]
[XmlInclude(typeof(ValueColorConverter_Band))]
[XmlInclude(typeof(ValueColorConverter_Gradient))]
public abstract class ValueColorConverter
{
    public abstract string Convert(double value);
}

[Serializable]
public class ValueColorConverter_Band : ValueColorConverter
{
    public override string Convert(double value)
    {
        //doo work
        
        return "";
    }
}

[Serializable]
public class ValueColorConverter_Gradient : ValueColorConverter
{
    public override string Convert(double value)
    {
        //doo work
        
        return "";
    }
}

I've seen many solutions presented where namespaces are used, but I haven't been able to adapt them for use without namespaces.

CodePudding user response:

You must deserialize into a concrete class, here ValueColorConverter_Gradient. Then you can assign the object to a variable of type ValueColorConverter.

CodePudding user response:

Well I figured it out. The issue turned out to be a typo in the XML. The 'xsi:type' needs to have a lower case 't'. Then it will deserialize into the derived type.

  • Related