我对 C# 消息序列化感到沮丧。
我有一个类,它有一个如下所示的构造函数:
public ProposalRequestMessage(int imaNumber, int proposalId, bool trainingFlag, string firstSiteAddress,
bool lastSiteFlag, string lastSiteAddress, int reasonCode,
List<LaneSelection> theLaneSelections)
{
ImaNumber = imaNumber;
ProposalId = proposalId;
TrainingFlag = trainingFlag;
FirstSiteAddress = firstSiteAddress;
LastSiteFlag = lastSiteFlag;
LastSiteAddress = lastSiteAddress;
ReasonCode = reasonCode;
laneSelections = new List<LaneSelection>(theLaneSelections);
}
System.Collections.Generic.List 类型的类的 lanesSelections 成员,其中 LaneSelection 如下所示:
public class LaneSelection
{
public int LaneId { get; set; }
public SignalAspect AspectCode { get; set; }
public LaneSelection()
{
}
public LaneSelection(int laneId, SignalAspect aspectCode)
{
LaneId = laneId;
AspectCode = aspectCode;
}
}
SignalAspect 是一个枚举。
我通过 MSMQ 发送包含此类实例的消息,如下所示:
System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(queuename);
queue.Purge();
System.Messaging.Message msg = new System.Messaging.Message(theMessage, new System.Messaging.XmlMessageFormatter());
queue.Send(msg);
使用一些调试工具,我发现生成的 XML 看起来有点像这样:
<?xml version="1.0"?>
<IvtmMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MessageType>ProposalRequest</MessageType>
<ProposalRequestMessage>
<ImaNumber>0</ImaNumber>
<ProposalId>2</ProposalId>
<TrainingFlag>false</TrainingFlag>
<FirstSiteAddress>M25/4690A</FirstSiteAddress>
<LastSiteFlag>false</LastSiteFlag>
<LastSiteAddress />
<ReasonCode>3</ReasonCode>
<LaneSelections>
<LaneSelection>
<LaneId>1</LaneId>
<AspectCode>Advisory20</AspectCode>
</LaneSelection>
</LaneSelections>
</ProposalRequestMessage>
我像这样反序列化另一端的消息:
Queue = new System.Messaging.MessageQueue(queueName);
Queue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(IvtmMessage) });
Queue.ReceiveCompleted += new System.Messaging.ReceiveCompletedEventHandler(Queue_ReceiveCompleted);
Queue.BeginReceive(new System.TimeSpan(0, 0, 0, 30));
...
System.Messaging.MessageQueue mq = (System.Messaging.MessageQueue)sender;
try
{
// End the asynchronous Receive operation.
System.Messaging.Message m = mq.EndReceive(e.AsyncResult);
IvtmMessage message = (IvtmMessage)m.Body;
DecodeMessage(message);
}
catch (System.Messaging.MessageQueueException ex)
{
string exception = ex.Message;
}
mq.BeginReceive();
return;
该类的每个成员都被正确反序列化,除了 laneSelections 元素,尽管它在 XML 中明确具有值,但在反序列化消息中计算为空实例。
在分离中,我尝试在类中添加一个列表,并在构造时用值 1-5 填充它。如果这个序列化正确,那么它会告诉我问题出在 LaneSelection 类上,但如果不是,那么问题将出在序列化 List 上。列表未正确序列化。
有谁知道出了什么问题?