C#类和结构
本文关键字:结构 | 更新日期: 2023-09-27 18:19:48
我在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
在类下,以及如何将其放入shape和GetObjectData中,因为我有太多的类必须使用这个结构
Thx
您可以直接用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));
}
}
与工作一样好的测试代码,我做了。