C# 优化以下代码添加注释 private bool Setushort address ushort startAddress float value string tutle int index int function = 6; 拼接报文 Listbyte byteList = new Listbyte
// 优化前的代码:
// 设置寄存器值 private bool Set(ushort address, ushort startAddress, float value, string tutle, int index) { int function = 6;
// 拼接报文
List<byte> byteList = new List<byte>()
{
// 地址 1个字节,取低位
(byte)(address%256),
// 功能码 1个字节 取低位
(byte)(function%256),
// 起始地址 2个字节 高位
(byte)(startAddress/256),
// 低位
(byte)(startAddress%256),
// 数据 2个字节 高位
(byte)(value/256),
// 低位
(byte)(value%256)
};
return Send(byteList, tutle, index);
}
// 发送报文
private bool Send(List
// 校验码
byteList = CRC16(byteList);
// 发送报文
port.Write(byteList.ToArray(), 0, byteList.ToArray().Length);
string str = "";
for (int i = 0; i < byteList.Count; i++)
{
str += byteList[i].ToString("x2") + " ";
}
modifyFile.Modify("报文", DateTime.Now.ToString($"yyyy-MM-dd HH:mm:ss:ffff:{title}发送报文"), str);
str = "";
Thread.Sleep(300);
byte[] buffer;
buffer = new byte[port.BytesToRead];
port.Read(buffer, 0, buffer.Length);
for (int i = 0; i < buffer.Length; i++)
{
str += buffer[i].ToString("x2") + " ";
}
modifyFile.Modify("报文", DateTime.Now.ToString($"yyyy-MM-dd HH:mm:ss:ffff:{title}接送报文"), str);
str = "";
return true;
}
catch (Exception ex) { Error = ex.Message; return false; }
}
// 优化后的代码:
// 设置寄存器值 private bool Set(ushort address, ushort startAddress, float value, string title, int index) { const int function = 6; // 功能码为常量,不需要每次都重新赋值
// 拼接报文
List<byte> byteList = new List<byte>()
{
// 地址 1个字节,取低位
(byte)(address % 256),
// 功能码 1个字节,取低位
(byte)(function),
// 起始地址 2个字节,高位
(byte)(startAddress / 256),
// 低位
(byte)(startAddress % 256),
// 数据 2个字节,高位
(byte)(value / 256),
// 低位
(byte)(value % 256)
};
return Send(byteList, title, index);
}
// 发送报文
private bool Send(List
// 校验码
List<byte> crcList = CRC16(byteList);
// 发送报文
port.Write(crcList.ToArray(), 0, crcList.Count); // 优化:直接使用 crcList.Count 作为数组长度
string str = string.Join(" ", crcList.Select(b => b.ToString("x2"))); // 优化:使用 LINQ 简化代码
modifyFile.Modify("报文", $"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff}:{title}发送报文", str); // 优化:使用字符串插值简化代码
Thread.Sleep(300);
byte[] buffer = new byte[port.BytesToRead];
port.Read(buffer, 0, buffer.Length);
str = string.Join(" ", buffer.Select(b => b.ToString("x2"))); // 优化:使用 LINQ 简化代码
modifyFile.Modify("报文", $"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff}:{title}接送报文", str); // 优化:使用字符串插值简化代码
return true;
}
catch (Exception ex)
{
Error = ex.Message;
return false;
}
}
原文地址: https://www.cveoy.top/t/topic/b6Rh 著作权归作者所有。请勿转载和采集!