Skip to main content
 首页 » 编程设计

c#之Microsoft MessageQueue Formatter 属性始终为空

2024年02月20日13pander-it

我在使用基本的 Microsoft Message Queue 实现时遇到以下问题:

在读取端,消息的 Formatter 属性始终为 null,无论我在发送端输入什么。

发送代码:

System.Messaging.Message m = new System.Messaging.Message("string to send"); 
m.Formatter = new XmlMessageFormatter( new Type[1] { typeof(string) } ); 
queue.Send(m, "label"); 

接收码:

MessageEnumerator enumerator = queue.GetMessageEnumerator2(); 
while (enumerator.MoveNext()) 
{ 
    Message m = enumerator.RemoveCurrent(); 
    Console.WriteLine("MSQ: " + m.Label); 
 
    Console.WriteLine("Formatter: " + m.Formatter.GetType().ToString()); // crash because formatter property is null 
 
    Console.WriteLine("Body: " + m.Body); //also crashes since formatter is null 
} 

由于 Formatter 为空,我也无法获得我最需要的 m.Body。

请您参考如下方法:

使用 MessageQueue.Formatter 属性反序列化消息。所以必须在接收代码中初始化MessageQueue.Formatter属性(queue.Formatter):

((XmlMessageFormatter)queue.Formatter).TargetTypes = new Type[1] { typeof(string) };