我在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中明显有值,但在反序列化消息中求值为null实例。
在解除分离中,我尝试将一个List添加到类中,并在构造时使用值1-5填充它。如果这个序列化正确,那么它会告诉我问题在于LaneSelection类,但如果没有,则问题在于序列化List。列表没有正确序列化。
有谁知道出了什么问题?
答案 0 :(得分:2)
您可能需要将[XmlInclude(typeof(LaneSelection))]属性添加到ProposalRequestMessage类中。
答案 1 :(得分:1)
两件事;
属性定义;
[XmlArray("LaneSelections"), XmlArrayElement("LaneSelection")]
public List<LaneSelection> LaneSelections { get; set; }
如果没有属性和类的正确Xml属性,您可以将它留给序列化程序来解释属性/对象应该如何翻译