다음을 통해 공유


XmlMessageFormatter 생성자

정의

XmlMessageFormatter 클래스의 새 인스턴스를 초기화합니다.

오버로드

Name Description
XmlMessageFormatter()

대상 형식을 설정하지 않고 클래스의 XmlMessageFormatter 새 인스턴스를 초기화합니다.

XmlMessageFormatter(String[])

클래스의 XmlMessageFormatter 새 인스턴스를 초기화하고 정규화된 문자열 값의 배열로 전달된 대상 형식을 설정합니다.

XmlMessageFormatter(Type[])

개체 형식의 XmlMessageFormatter 배열로 전달된 대상 형식을 설정하여 클래스의 새 인스턴스를 초기화합니다.

XmlMessageFormatter()

대상 형식을 설정하지 않고 클래스의 XmlMessageFormatter 새 인스턴스를 초기화합니다.

public:
 XmlMessageFormatter();
public XmlMessageFormatter();
Public Sub New ()

설명

생성자의 이 오버로드는 작성할 때 대상 형식이 필요하지 않으므로 큐에 쓸 때 가장 자주 사용됩니다.

이 생성자를 사용하여 만든 인스턴스 XmlMessageFormatter 를 사용하여 큐에서 메시지를 읽으려면 포맷터가 역직렬화하려는 형식을 알 수 있도록 또는 TargetTypes 속성을 설정 TargetTypeNames 해야 합니다.

MessageQueue인스턴스를 만들면 대상 형식을 설정하지 않고 기본 XmlMessageFormatter 인스턴스가 만들어집니다. 이 생성자를 사용하여 만든 포맷터와 마찬가지로 큐에서 읽으려면 해당 포맷터 인스턴스에 대한 대상 형식을 설정해야 합니다.

적용 대상

XmlMessageFormatter(String[])

클래스의 XmlMessageFormatter 새 인스턴스를 초기화하고 정규화된 문자열 값의 배열로 전달된 대상 형식을 설정합니다.

public:
 XmlMessageFormatter(cli::array <System::String ^> ^ targetTypeNames);
public XmlMessageFormatter(string[] targetTypeNames);
new System.Messaging.XmlMessageFormatter : string[] -> System.Messaging.XmlMessageFormatter
Public Sub New (targetTypeNames As String())

매개 변수

targetTypeNames
String[]

제공된 메시지에서 포맷터에 의해 역직렬화될 가능한 형식 집합을 지정하는 형식 String 의 배열입니다. 이러한 값은 정규화되어야 합니다(예: "MyNamespace.MyOrders, MyOrdersAssemblyName").

예외

매개 변수는 targetTypeNames .입니다 null.

예제

#using <system.dll>
#using <system.messaging.dll>
#using <system.drawing.dll>

using namespace System;
using namespace System::Messaging;
using namespace System::Drawing;
using namespace System::IO;
ref class Order
{
public:
   int orderId;
   DateTime orderTime;
};

ref class MyNewQueue
{
public:
   static void CreateQueue( String^ queuePath )
   {
      try
      {
         if (  !MessageQueue::Exists( queuePath ) )
         {
            MessageQueue::Create( queuePath );
         }
         else
         {
            Console::WriteLine(  "{0} already exists.", queuePath );
         }
      }
      catch ( MessageQueueException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   void SendMessage()
   {
      try
      {
         // Create a new order and set values.
         Order^ sentOrder = gcnew Order;
         sentOrder->orderId = 3;
         sentOrder->orderTime = DateTime::Now;

         // Connect to a queue on the local computer.
         MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

         // Create the new order.
         Message^ myMessage = gcnew Message( sentOrder );

         // Send the order to the queue.
         myQueue->Send( myMessage );
      }
      catch ( ArgumentException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

      return;
   }

   void ReceiveMessage()
   {
      // Connect to the a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

      // Set the formatter to indicate body contains an Order.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = Order::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );
      try
      {
         // Receive and format the message. 
         Message^ myMessage = myQueue->Receive();
         Order^ myOrder = dynamic_cast<Order^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( "Order ID: {0}", myOrder->orderId );
         Console::WriteLine( "Sent: {0}", myOrder->orderTime );
      }
      catch ( MessageQueueException^ ) 
      {
         // Handle Message Queuing exceptions.
      }
      // Handle invalid serialization format.
      catch ( InvalidOperationException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

      // Catch other exceptions as necessary.
      return;
   }
};

int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

   // Create a queue on the local computer.
   MyNewQueue::CreateQueue( ".\\myQueue" );

   // Send a message to a queue.
   myNewQueue->SendMessage();

   // Receive a message from a queue.
   myNewQueue->ReceiveMessage();
   return 0;
}
using System;
using System.Messaging;
using System.Drawing;
using System.IO;

namespace MyProject
{

    // The following example
    // sends to a queue and receives from a queue.
    public class Order
    {
        public int orderId;
        public DateTime orderTime;
    };	

    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue
    {

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example sends and receives a message from
        // a queue.
        //**************************************************

        public static void Main()
        {
            // Create a new instance of the class.
            MyNewQueue myNewQueue = new MyNewQueue();

            // Create a queue on the local computer.
            CreateQueue(".\\myQueue");
            
            // Send a message to a queue.
            myNewQueue.SendMessage();

            // Receive a message from a queue.
            myNewQueue.ReceiveMessage();

            return;
        }

        //**************************************************
        // Creates a new queue.
        //**************************************************

        public static void CreateQueue(string queuePath)
        {
            try	
            {
                if(!MessageQueue.Exists(queuePath))
                {
                    MessageQueue.Create(queuePath);
                }
                else
                {
                    Console.WriteLine(queuePath + " already exists.");
                }
            }
            catch (MessageQueueException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        //**************************************************
        // Sends an Order to a queue.
        //**************************************************
        
        public void SendMessage()
        {
            try
            {

                // Create a new order and set values.
                Order sentOrder = new Order();
                sentOrder.orderId = 3;
                sentOrder.orderTime = DateTime.Now;

                // Connect to a queue on the local computer.
                MessageQueue myQueue = new MessageQueue(".\\myQueue");

                // Create the new order.
                Message myMessage = new Message(sentOrder);

                // Send the order to the queue.
                myQueue.Send(myMessage);
            }
            catch(ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            return;
        }

        //**************************************************
        // Receives a message containing an order.
        //**************************************************
        
        public  void ReceiveMessage()
        {
            // Connect to the a queue on the local computer.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            // Set the formatter to indicate body contains an Order.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(MyProject.Order)});
            
            try
            {
                // Receive and format the message.
                Message myMessage =	myQueue.Receive();
                Order myOrder = (Order)myMessage.Body;

                // Display message information.
                Console.WriteLine("Order ID: " +
                    myOrder.orderId.ToString());
                Console.WriteLine("Sent: " +
                    myOrder.orderTime.ToString());
            }
            
            catch (MessageQueueException)
            {
                // Handle Message Queuing exceptions.
            }

                // Handle invalid serialization format.
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
            
            // Catch other exceptions as necessary.

            return;
        }
    }
}
Imports System.Messaging
Imports System.Drawing
Imports System.IO



   
' The following example 
' sends to a queue and receives from a queue.
Public Class Order
      Public orderId As Integer
      Public orderTime As DateTime
End Class

   
  
' Provides a container class for the example.

Public Class MyNewQueue
      
      

   ' Provides an entry point into the application.
   '		 
   ' This example sends and receives a message from
   ' a queue.

   Public Shared Sub Main()
      ' Create a new instance of the class.
      Dim myNewQueue As New MyNewQueue()
        
      ' Create a queue on the local computer.
      CreateQueue(".\myQueue")
         
      ' Send a message to a queue.
      myNewQueue.SendMessage()
       
      ' Receive a message from a queue.
      myNewQueue.ReceiveMessage()
         
      Return
   End Sub
      
      

      ' Creates a new queue.
   Public Shared Sub CreateQueue(queuePath As String)
      Try
         If Not MessageQueue.Exists(queuePath) Then
            MessageQueue.Create(queuePath)
         Else
            Console.WriteLine((queuePath + " already exists."))
         End If
      Catch e As MessageQueueException
         Console.WriteLine(e.Message)
      End Try
   End Sub
       
      

      ' Sends an Order to a queue.

   Public Sub SendMessage()
      Try
            
            ' Create a new order and set values.
            Dim sentOrder As New Order()
            sentOrder.orderId = 3
            sentOrder.orderTime = DateTime.Now
            
            ' Connect to a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myQueue")
            
            
            
            ' Create the new order.
            Dim myMessage As New Message(sentOrder)
            
            ' Send the order to the queue.
            myQueue.Send(myMessage)
      Catch e As ArgumentException
            Console.WriteLine(e.Message)
      End Try 
         
      Return
   End Sub
      
      
      
 
      ' Receives a message containing an order.
 
   Public Sub ReceiveMessage()
         ' Connect to the a queue on the local computer.
         Dim myQueue As New MessageQueue(".\myQueue")
         
         ' Set the formatter to indicate body contains an Order.
         myQueue.Formatter = New XmlMessageFormatter(New Type() {GetType(Order)})
         
         Try
            ' Receive and format the message. 
            Dim myMessage As Message = myQueue.Receive()
            Dim myOrder As Order = CType(myMessage.Body, Order)
            
            ' Display message information.
            Console.WriteLine(("Order ID: " + myOrder.orderId.ToString()))
            Console.WriteLine(("Sent: " + myOrder.orderTime.ToString()))
         
  
         ' Handle invalid serialization format.
         Catch e As InvalidOperationException
            Console.WriteLine(e.Message)
         End Try
         
         ' Catch other exceptions as necessary.
         Return
   End Sub
End Class

설명

대상 형식 매개 변수가 있는 생성자는 큐에서 읽을 때 가장 자주 사용됩니다. 작성할 때 대상 형식을 지정할 필요는 없습니다.

생성자의 이 오버로드는 XmlMessageFormatter 매개 변수를 통해 targetTypeNames 전달된 배열 값으로 속성을 설정합니다TargetTypeNames. 이 속성을 설정하면 이 XmlMessageFormatter 인스턴스를 MessageQueue 사용하여 지정된 형식의 개체가 포함된 메시지를 읽을 수 있습니다.

TargetTypeNames TargetTypes 두 속성 모두 메시지를 역직렬화할 때 일치시킬 스키마를 포맷터에 알려줍니다. 이렇게 하면 포맷터가 메시지 본문을 해석할 수 있습니다.

메시지 본문에 직렬화된 인스턴스는 형식 배열에 표시되는 스키마 중 하나를 준수해야 합니다. 메서드를 사용하여 Receive 메시지를 읽을 때 메서드는 식별된 스키마에 해당하는 형식의 개체를 만들고 메시지 본문을 읽습니다.

큐에서 읽을 때는 두 속성 중 하나만 설정해야 하지만 둘 다 설정할 수 있습니다. 형식 집합은 두 속성에서 결합된 집합입니다. 사용할 결정 사항은 애플리케이션에 따라 결정됩니다. 메시지 본문에 스키마가 두 속성에 대한 배열의 형식과 일치하지 않는 형식이 포함되어 있으면 읽기 시간에 예외가 throw됩니다.

적용 대상

XmlMessageFormatter(Type[])

개체 형식의 XmlMessageFormatter 배열로 전달된 대상 형식을 설정하여 클래스의 새 인스턴스를 초기화합니다.

public:
 XmlMessageFormatter(cli::array <Type ^> ^ targetTypes);
public XmlMessageFormatter(Type[] targetTypes);
new System.Messaging.XmlMessageFormatter : Type[] -> System.Messaging.XmlMessageFormatter
Public Sub New (targetTypes As Type())

매개 변수

targetTypes
Type[]

제공된 메시지에서 포맷터에 의해 역직렬화될 가능한 형식 집합을 지정하는 형식 Type 의 배열입니다.

예외

매개 변수는 targetTypes .입니다 null.

설명

대상 형식 매개 변수가 있는 생성자는 큐에서 읽을 때 가장 자주 사용됩니다. 작성할 때 대상 형식을 지정할 필요는 없습니다.

생성자의 이 오버로드는 XmlMessageFormatter 매개 변수를 통해 targetTypes 전달된 배열 값으로 속성을 설정합니다TargetTypes. 이 속성을 설정하면 이 XmlMessageFormatter 인스턴스를 MessageQueue 사용하여 지정된 형식의 개체가 포함된 메시지를 읽을 수 있습니다.

TargetTypeNames TargetTypes 두 속성 모두 메시지를 역직렬화할 때 일치시킬 스키마를 포맷터에 알려줍니다. 이렇게 하면 포맷터가 메시지 본문을 해석할 수 있습니다.

메시지 본문에 직렬화된 인스턴스는 형식 배열에 표시되는 스키마 중 하나를 준수해야 합니다. 메서드를 사용하여 Receive 메시지를 읽을 때 메서드는 식별된 스키마에 해당하는 형식의 개체를 만들고 메시지 본문을 읽습니다.

큐에서 읽을 때는 두 속성 중 하나만 설정해야 하지만 둘 다 설정할 수 있습니다. 형식 집합은 두 속성에서 결합된 집합입니다. 사용할 결정 사항은 애플리케이션에 따라 결정됩니다. 메시지 본문에 스키마가 두 속성에 대한 배열의 형식과 일치하지 않는 형식이 포함되어 있으면 읽기 시간에 예외가 throw됩니다.

대신 TargetTypeNames지정할 TargetTypes 때 형식 존재는 읽기 시간이 아닌 컴파일 시간에 확인되므로 오류 가능성이 줄어듭니다. TargetTypeNames 에서는 모든 항목이 정규화되고 해당 어셈블리 이름을 지정해야 합니다. 또한 여러 동시 버전으로 작업하는 경우 대상 형식 이름에도 버전 번호를 추가해야 합니다.

사용하는 TargetTypes경우 다음 C# 코드에서 보여 준 방식으로 각 개체(예 MyClass: )를 목록에 추가할 수 있습니다.

TargetTypes = new Type[]{typeof(MyClass)}

적용 대상