Visual C++ .NET/Class/IComparable — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:05, 26 мая 2010

generic comparable

 
#include "stdafx.h"
using namespace System;
enum class SortByEnum
{
   SortByDate,
   SortByFrom,
   SortBySubject
};
ref class MyEmail : IComparable<MyEmail^>
{
   public:
   static property SortByEnum SortCriterion;
   property DateTime DateReceived;
   property String^ From;
   property String^ Subject;
   property String^ Body;
   MyEmail(DateTime dt, String^ from, String^ subject, String^ body)
   {
      DateReceived = dt;
      From = from;
      Subject = subject;
      Body = body;
   }
   virtual int CompareTo(MyEmail^ msg)
   {
       switch ( SortCriterion )
       {
           case SortByEnum::SortByDate:
              return this->DateReceived.rupareTo(msg->DateReceived);
           case SortByEnum::SortByFrom:
              return this->From->CompareTo(msg->From);
           case SortByEnum::SortBySubject:
              return this->Subject->CompareTo(msg->Subject);
           default:
              throw gcnew InvalidOperationException();
       }
   }
};
void PrintHeaders(array<MyEmail^>^ messages, SortByEnum sortOrder){
   MyEmail::SortCriterion = sortOrder;
   Array::Sort(messages);
   for (int i = 0; i < messages->Length; i++)
   {
       Console::WriteLine("Received: {0} From: <{1}> Subject: {2}",messages[i]->DateReceived, messages[i]->From,messages[i]->Subject );
   }
}
int main(){
   array<MyEmail^>^ message_array ={
      gcnew MyEmail( DateTime(2006, 1, 12), "N", "D", ""),
      gcnew MyEmail( DateTime(2006, 1, 15), "G", "B", ""),
      gcnew MyEmail( DateTime(2006, 1, 2), "G", "B", ""),
      gcnew MyEmail( DateTime(2005, 12, 31), "J","W", "")
   };
   PrintHeaders(message_array, SortByEnum::SortByDate);
   PrintHeaders(message_array, SortByEnum::SortByFrom);
   PrintHeaders(message_array, SortByEnum::SortBySubject);
}