我在C#中序列化有些问题 有代码:
public struct CoOrds
{
public double x, y, z;
public CoOrds(double p1, double p2, double p3)
{
x = p1;
y = p2;
z = p3;
}
}
public struct printColor
{
public int r, g, b;
public printColor(int p1, int p2, int p3)
{
r = p1;
g = p2;
b = p3;
}
}
[Serializable]
public abstract class shape : ISerializable
{
public int borderStyle=1;
/* ===============================COLOR PARAMETERS================================ */
public printColor colorRGB = new printColor(0, 0, 0);
public System.Drawing.Drawing2D.DashStyle styleLine { get; set; }
public int widht=2;
/*=================================FILL PARAMETERS=====================================*/
public printColor fillColorRGB = new printColor(255,255, 255);
public shape()
{
}
protected shape(SerializationInfo info, StreamingContext context)
{
colorRGB.r = info.GetInt32("colorLine.r");
colorRGB.g = info.GetInt32("colorLine.g");
colorRGB.b = info.GetInt32("colorLine.b");
borderStyle = info.GetInt32("borderStyle");
fillColorRGB.r = info.GetInt32("fillColorRGB.r");
fillColorRGB.g = info.GetInt32("fillColorRGB.g");
fillColorRGB.b = info.GetInt32("fillColorRGB.b");
widht = info.GetInt32("widht");
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("colorLine.r",colorRGB.r);
info.AddValue("colorLine.g", colorRGB.g);
info.AddValue("colorLine.b", colorRGB.b);
info.AddValue("borderStyle",borderStyle);
info.AddValue("fillColorRGB.r", fillColorRGB.r);
info.AddValue("fillColorRGB.g", fillColorRGB.g);
info.AddValue("fillColorRGB.b", fillColorRGB.b);
info.AddValue("widht", widht);
}
.....
1。我怎么可以序列化结构像
[Serializable]
public struct CoOrds
在类下面以及如何将它放在形状和GetObjectData中,因为我有太多的类我必须使用这个结构
THX
答案 0 :(得分:1)
您可以使用info.AddValue("Pos", pos, typeof(CoOrds)
直接序列化,也可以转换为string
。
[Serializable()]
public struct Coords
{
readonly public double x, y, z;
public Coords(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static Coords FromString(string value)
{
if (string.IsNullOrEmpty(value)) return new Coords();
double x = 0,y= 0,z = 0;
string[] parts = value.Split(',');
if (parts.Length > 0) double.TryParse(parts[0], out x);
if (parts.Length > 1) double.TryParse(parts[1], out y);
if (parts.Length > 2) double.TryParse(parts[2], out z);
return new Coords(x, y, z);
}
public override string ToString()
{
//Ensure round-trip formatting
return string.Format("{0:R},{1:R},{2:R}", x, y, z);
}
}
然后用
序列化它[Serializable()]
public class Vertex : ISerializable
{
public Coords pos1, pos2;
...
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Pos1", pos1.ToString());
info.AddValue("Pos2", pos2, typeof(Coords));
}
public Vertex(SerializationInfo info, StreamingContext context)
{
this.pos1 = Coords.FromString(info.GetValue("Pos1", typeof(string)) as string);
this.pos2 = (Coords)info.GetValue("Pos2", typeof(Coords));
}
}
我的测试代码同样适用。