using System;
using System.Xml.Serialization;
using System.IO;
public class Test
{
public static void Main()
{
Sub subInstance = new Sub();
Console.WriteLine(subInstance.TestMethod());
}
public class Super
{
public string TestMethod() {
return this.SerializeObject();
}
}
public class Sub : Super
{
}
}
public static class TestExt {
public static string SerializeObject<T>(this T toSerialize)
{
Console.WriteLine(typeof(T).Name); // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter textWriter = new StringWriter();
// And now...this will throw and Exception!
// Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType());
// solves the problem
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uWG1sLlNlcmlhbGl6YXRpb247CnVzaW5nIFN5c3RlbS5JTzsKCnB1YmxpYyBjbGFzcyBUZXN0CnsKICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBNYWluKCkKICAgIHsKICAgICAgICBTdWIgc3ViSW5zdGFuY2UgPSBuZXcgU3ViKCk7CiAgICAgICAgQ29uc29sZS5Xcml0ZUxpbmUoc3ViSW5zdGFuY2UuVGVzdE1ldGhvZCgpKTsKICAgIH0KICAgICAKICAgIHB1YmxpYyBjbGFzcyBTdXBlcgogICAgewogICAgICAgIHB1YmxpYyBzdHJpbmcgVGVzdE1ldGhvZCgpIHsKICAgICAgICAgICAgcmV0dXJuIHRoaXMuU2VyaWFsaXplT2JqZWN0KCk7CiAgICAgICAgfQogICAgfQogICAgIAogICAgcHVibGljIGNsYXNzIFN1YiA6IFN1cGVyCiAgICB7CiAgICB9Cn0KCnB1YmxpYyBzdGF0aWMgY2xhc3MgVGVzdEV4dCB7CiAgICBwdWJsaWMgc3RhdGljIHN0cmluZyBTZXJpYWxpemVPYmplY3Q8VD4odGhpcyBUIHRvU2VyaWFsaXplKQogICAgewogICAgICAgI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