在同样的项目中,采用了json文件来序列化和反序列化重要的参数。
下图是程序的结构,可以看到序列化和反序列化在Common\ProgramParam.cs中
public class ProgramParam
{
public string VisionInterfaceName; // 视觉接口名
public string VisionDeviceName; // 视觉设备名
public string VisionCameraType; // 视觉设备类型
public string SerialName; // COM
public int BaudRate; // 波特率
public int DataBit; // 数据位
public string CheckBit; // 校验位
public string StopBit; // 停止位
public bool IsASCII; // ASCII格式
//Find_Nail配置参数:
public int UpLeftX; //左上角坐标X
public int UpLeftY; //左上角坐标Y
public int DownRightX; //右下角坐标X
public int DownRightY; //右下角坐标Y
public int GrayValue; //灰度值
public int AreaFrom; //面积起始值
public int AreaTo; //面积终止值
public double Crevice; //钉子上的缝隙宽度值
private const string SavePath = @"../config/ProgramParam.json";
可以看到这些重要的参数,以及json文件存储的路径。
public ProgramParam() { }
[JsonConstructor]
public ProgramParam(string visionInterfaceName, string visionDeviceName,
string serialName, int baudRate, int dataBit,
string checkBit, string stopBit, bool isAscii,
int upLeftX, int upLeftY, int downRightX, int downRightY,
int grayValue, int areaFrom, int areaTo, double crevice)
{
VisionInterfaceName = visionInterfaceName;
VisionDeviceName = visionDeviceName;
SerialName = serialName;
BaudRate = baudRate;
DataBit = dataBit;
CheckBit = checkBit;
StopBit = stopBit;
IsASCII = isAscii;
UpLeftX = upLeftX;
UpLeftY = upLeftY;
DownRightX = downRightX;
DownRightY = downRightY;
GrayValue = grayValue;
AreaFrom = areaFrom;
AreaTo = areaTo;
Crevice = crevice;
}
在构造函数中有赋值操作。
// 序列化
public void Save()
{
using (var file = File.CreateText(SavePath))
{
var serializer = new JsonSerializer
{
Formatting = Formatting.Indented
};
serializer.Serialize(file, this);
}
}
然后是序列化和反序列化
// 反序列化
public static ProgramParam Load()
{
var result = new ProgramParam();
if (File.Exists(SavePath))
{
using (var file = File.OpenText(SavePath))
{
var serializer = new JsonSerializer();
result = (ProgramParam)serializer.Deserialize(file, typeof(ProgramParam));
}
}
return result;
}