我使用XmlSerializer
和StreamWriter
序列化/反序列化包含双值的对象。在生成的.xml
文件中,我发现double值存储为十进制值。我有没有办法生成十六进制形式的双倍而不是十进制?
一些代码。
要序列化的课程
[Serializable()]
public class Variable
{
public int shift;
public int size;
public int min;
public int max;
public string name;
public string del;
public Variable()
{
shift = 26;
size = 0;
min = 0;
max = 0;
name = "noname";
del = "-";
}
}
序列化作家类
/// <summary>
/// class to serialize/deserialize another class
/// </summary>
public class serializator
{
private serializator()
{
}
/// <summary>
/// serializator
/// </summary>
/// <param name="fname">filename to serialize</param>
/// <param name="z">object to serialize</param>
static public void ser(string fname, object z)
{
System.Type st = z.GetType();
XmlSerializer xSer = new XmlSerializer(st);
StreamWriter sWri = new StreamWriter(fname);
xSer.Serialize(sWri, z);
sWri.Close();
}
/// <summary>
/// deserializator
/// usage: fooclass fc = (fooclass)serializator.dser("fname.xml", fc);
/// </summary>
/// <param name="fname">filename to dser</param>
/// <param name="z">object to grab type</param>
/// <returns></returns>
static public object dser(string fname, object z)
{
if (fname != null && fname != "" && z != null)
{
try
{
object rez = new object();
XmlSerializer xSer = new XmlSerializer(z.GetType());
StreamReader sRea = new StreamReader(fname);
rez = xSer.Deserialize(sRea);
sRea.Close();
return rez;
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show("config ouch\r\n"+e.Message);
return null;
}
}
else
{
return null;
}
}
}
主程序代码
Variable v = new Variable();
serializator.ser("foo.xml", v);
生成的xml文件
<?xml version="1.0" encoding="utf-8"?>
<Variable>
<shift>26</shift>
<size>0</size>
<min>0</min>
<max>0</max>
<name>noname</name>
<del>-</del>
</Variable>
在这种特殊情况下,我希望<shift>1A</shift>
或<shift>0x1A</shift>
代替<shift>26</shift>
。有可能吗?
答案 0 :(得分:2)
您可以使用“变量”类代码而不是您的代码:
[Serializable()]
public class Variable
{
int _shiftInt;
public string shift
{
get
{
return _shiftInt.ToString("X");
}
set
{
_shiftInt = int.Parse(value, System.Globalization.NumberStyles.HexNumber);
}
}
public int size { get; set; }
public int min { get; set; }
public int max { get; set; }
public string name { get; set; }
public string del { get; set; }
public Variable()
{
_shiftInt = 26;
size = 0;
min = 0;
max = 0;
name = "noname";
del = "-";
}
}