简体   繁体   English

Xml序列化失败与隐式类型转换器

[英]Xml Serialization Failure with implicit type converter

The following code throws a runtime error on Windows 7 but not on Windows 8. 以下代码在Windows 7而非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. 确保您的程序集和引用的System.Drawing程序集都具有相同的.net版本。 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) 当启动程序集设置为.NET Framework 4 Client Profile,并且引用程序集设置为.NET Framework 4(右键单击,属性,应用程序)时,我已经看到此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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