【发布时间】:2019-04-14 17:13:31
【问题描述】:
我正在尝试序列化一个没有另一个可序列化类的无参数构造函数的子类。 无论我如何尝试,由于没有无参数构造函数,我总是得到 InvalidOperationException。
我尝试将我的子类转换为基类:simlpe 转换(通过简单转换,我的意思是中间有所需类型的括号)和 Convert.ChangeType(...)。虽然前者不起作用(我仍然得到异常),但后一种方法会导致 InvalidCastException(消息说对象必须实现 IConvertible 接口)。
这是完全可序列化的基类:
[XmlRoot("NdSRD_Environment")]
public class Environment
{
#pragma warning disable IDE1006 // Naming Styles
[XmlAttribute]
public string id { get; set; }
[XmlElement]
public double realWidth { get; set; }
[XmlElement]
public double realHeight { get; set; }
[XmlElement]
public double realDepth { get; set; }
[XmlElement]
public int PIXEL_WIDTH { get; set; }
[XmlElement]
public int PIXEL_HEIGHT { get; set; }
[XmlElement]
public int PIXEL_DEPTH { get; set; }
[XmlArrayItem(ElementName ="Height")]
[XmlArray]
public List<short> heights { get; set; }
[XmlElement]
public int worldWidthSegments { get; set; }
[XmlElement]
public int worldDepthSegments { get; set; }
#pragma warning restore IDE1006 // Naming Styles
}
这是产生错误的子类:
public class FlatEnvironment : NdSRD.WebService.Core.DataModel.Environment
{
public readonly static int PIXEL_PER_REAL_METER_RATIO = 100;
public FlatEnvironment(double realWidth, double realDepth, double maxHeight)
{
this.PIXEL_WIDTH = (int)realWidth * PIXEL_PER_REAL_METER_RATIO;
this.PIXEL_DEPTH = (int)realDepth * PIXEL_PER_REAL_METER_RATIO;
this.PIXEL_HEIGHT = (int)maxHeight * PIXEL_PER_REAL_METER_RATIO;
this.worldWidthSegments = 128;
this.worldDepthSegments = 128;
this.id = "FLAT_ENVIRONMENT-WxDxmH:" + realWidth + "x" + realDepth + "x" + maxHeight + "-PWxPDxPH:" + PIXEL_WIDTH + "x" + PIXEL_DEPTH + "x" + PIXEL_HEIGHT + " WSxDS:" + this.worldWidthSegments + "x" + this.worldDepthSegments;
this.realWidth = realWidth;
this.realDepth = realDepth;
this.realHeight = maxHeight;
this.heights = new System.Collections.Generic.List<short>();
for (int i = 0; i < (this.worldDepthSegments + 1) * (this.worldWidthSegments + 1); i++)
{
heights.Add(0);
}
}
}
更新 1: 这是我对提到的类进行序列化的方式:
public void Serialize(string fileName, NdSRD.WebService.Core.DataModel.Environment environment)
{
XmlSerializer xs = new XmlSerializer(typeof(NdSRD.WebService.Core.DataModel.Environment));
System.IO.TextWriter writer = new StreamWriter(fileName);
xs.Serialize(writer, environment);
writer.Close();
}
【问题讨论】:
-
您的
FlatEnvironment类是否仅包含readonly static int和构造函数,还是实际上具有特定于该类的方法?
标签: c#