简体   繁体   中英

Xml Serialization Failure with implicit type converter

The following code throws a runtime error on Windows 7 but not on Windows 8.

public struct PointD
{
  public double X { get; set; }
  public double Y { get; set; }

  public static implicit operator PointD(Point point)
  {
    return new PointD() { X = point.X, Y = point.Y };
  }
}

var p = new PointD();
XmlSerializer serializer = new XmlSerializer(typeof(PointD));
using (var stream = File.Create("test.xml"))
  serializer.Serialize(stream, p);

The error is:

Unable to generate a temporary class (result=1).
error CS0012: The type 'System.Drawing.Point' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Drawing, Version=4.0.0.0, 
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Any ideas?

I don't know what the cause of the problem is, but I've found a way to fix it:

Replace this line

XmlSerializer serializer = new XmlSerializer(typeof(PointD));

with something like this:

XmlSerializer serializer = new XmlSerializer(typeof(PointD), new Type[]{typeof(Point)});

Make sure your assembly and the referenced System.Drawing assembly both have the same .net version. I've seen this error when the start-up assembly is set to .NET framework 4 Client Profile, and the ref'd assembly is set to .NET framework 4 (right click, properties, application)

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