【发布时间】:2020-01-06 03:45:11
【问题描述】:
我有一个 C# winforms 应用程序。在此应用程序中,我从 xml 文件动态创建 CanMessage 对象列表。
xml文件构造如下
<message id="0x641" ecu="BCM" name="BODY9" dlc="8" cyclicrate="500">
<bytes>
<byte0>0x0</byte0>
<byte1>0x0</byte1>
<byte2>0x0</byte2>
<byte3>0x0</byte3>
<byte4>0x0</byte4>
<byte5>0x0</byte5>
<byte6>0x0</byte6>
<byte7>0x0</byte7>
</bytes>
Canmessage 对象的构造如下:
CanMessage(String name,String _EcuName, ulong id, ushort dlc,int[] bytearray , int cyclic)
{
this.Name = name;
this.EcuName = _EcuName;
this.Id = id;
this.Dlc = dlc;
this.Bytes = new int[dlc];
this.CyclicRate = cyclic;
int i = 0;
for(i = 0; i < dlc; i++)
{
this.Bytes[i] = bytearray[i];
}
}
以下是我如何构建我的Canmessage 列表:
public void BuildCanList()
{
try
{
XmlDocument xd = new XmlDocument();
xd.Load(XmlFile);
XmlNodeList nodelist = xd.SelectNodes("/messages/message");
foreach (XmlNode n in nodelist)
{
String name, ecuname;
ulong id;
ushort dlc;
int[] bytes = new int[Convert.ToInt32(n.Attributes.GetNamedItem("dlc").Value)];
int cyclic;
name = n.Attributes.GetNamedItem("name").Value.ToString();
id = (ulong)Convert.ToInt32(n.Attributes.GetNamedItem("id").Value, 16);
ecuname = n.Attributes.GetNamedItem("ecu").Value.ToString();
dlc = (ushort)Convert.ToByte(n.Attributes.GetNamedItem("dlc").Value);
cyclic = Convert.ToInt32(n.Attributes.GetNamedItem("cyclicrate").Value);
XmlNode sn = n.SelectSingleNode("bytes");
for (ushort i = 0; i < dlc; i++)
{
try
{
bytes[i] = Convert.ToInt32(sn.ChildNodes.Item(i).InnerText, 16);
}
catch(Exception e)
{
bytes[i] = 0x0;
Console.WriteLine(String.Format("Error Building can Message: {0}", e.ToString()));
}
}
CanMessage cm = new CanMessage(name, ecuname, id, dlc, bytes, cyclic);
CanList.Add(cm);
}
我的列表正在创建,没有任何问题。我的问题是,在我的列表创建之后,我有时需要对某个 Canmessage 的某些字节进行一些位操作。如何根据name 属性从列表中选择一条消息,然后编辑该消息中的某些字节?我知道如何使用 lambda 表达式和 linq 从列表中选择一条消息。但我不知道如何将该选择方法与编辑和保存方法结合起来,或者这是否是最好的方法。
【问题讨论】:
-
什么意思?请注意,您可以使用字典直接访问具有名称(键值对)的对象。从那里您将获得该值,然后您可以像往常一样编辑它,而无需
linq表达式。 -
如果您不知道,您也可以使用 Lookup 并拥有 1 个具有多个值的键(以防 1 个名称多次出现)
-
从xml读入对象是反序列化。然后,您可以将列表编辑为任何列表。保存将是序列化。请参阅this answer 了解序列化和反序列化以及编辑将与编辑任何列表或对象相同。
-
1) 反序列化 2) 在内存中编辑 3) 序列化。或者直接编辑 XML 文件。