에어버스 2018. 4. 7. 17:46

// ConsoleApplication1.cpp : 기본  프로젝트 파일입니다.

#include "stdafx.h"

#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::ComponentModel;
using namespace System::Windows::Forms;

public delegate void FirstEventHandler(String^);
public delegate void SecondEventHandler(String^);

public delegate double NumericOp(double);


ref class Ops
{
public:
 event FirstEventHandler^ OnFirstEvent;
 event SecondEventHandler^ OnSecondEvent;

 void RaiseOne(String^ pMsg)
 {
  OnFirstEvent(pMsg);
 }
 void RaiseTwo(String^ pMsg)
 {
  OnSecondEvent(pMsg);
 }

 /*
public:
 static double square(double d)
 {
  Console::WriteLine("square");
  return d * d;
 }
 static double square3(double d)
 {
  Console::WriteLine("square3");
  return d * d * d;
 }
 */
};

//__gc public CppForm : public Form // 1세대용
public ref class CppForm : public Form
{
public:
 CppForm() {};
};

ref class EvtRcv1
{
 Ops^ theSource;

public:
 EvtRcv1(Ops^ pSrc)
 {
  //if (pSrc == 0)
  // throw gcnew ArgumentNullException("이벤트 소스가 필요합니다.");
  theSource = pSrc;
  theSource->OnFirstEvent += gcnew FirstEventHandler(this, &EvtRcv1::FirstEvent);
  theSource->OnSecondEvent += gcnew SecondEventHandler(this, &EvtRcv1::SecondEvent);
 }

 void FirstEvent(String^ pMsg)
 {
  Console::WriteLine("EvtRcv1 : 이벤트1, 메세지는 {0}", pMsg);
 }

 void SecondEvent(String^ pMsg)
 {
  Console::WriteLine("EvtRcv1 : 이벤트2, 메세지는 {0}", pMsg);
 }

 void RemoveHandler()
 {
  theSource->OnFirstEvent -= gcnew FirstEventHandler(this, &EvtRcv1::FirstEvent);
 }
};


int main(array<System::String ^> ^args)
{
 Ops^ pSrc = gcnew Ops();
 EvtRcv1^ pRcv = gcnew EvtRcv1(pSrc);
 pSrc->RaiseOne("Hello");
 pSrc->RaiseTwo("One big step");
 pRcv->RemoveHandler();
 Console::WriteLine("==========================");
 pSrc->RaiseOne("Hello1");
 pSrc->RaiseTwo("Two bic step");


 Console::ReadKey();

 /*
 //Ops^ a = gcnew Ops;
 NumericOp^ pOp = gcnew NumericOp(&Ops::square); // new 대신 gcnew, * 대신 ^ 사용
 NumericOp^ pOp2 = gcnew NumericOp(&Ops::square3); // new 대신 gcnew, * 대신 ^ 사용
 NumericOp^ pOp5 = gcnew NumericOp(&Ops::square); // new 대신 gcnew, * 대신 ^ 사용

 NumericOp^ pOp3 = dynamic_cast<NumericOp^>(Delegate::Combine(pOp, pOp2));
 NumericOp^ pOp4 = dynamic_cast<NumericOp^>(Delegate::Combine(pOp3, pOp5));
 double result = pOp->Invoke(3.0);
 Console::WriteLine("Result : {0}", result);
 result = pOp2->Invoke(3.0);
 Console::WriteLine("Result : {0}", result);
 Console::WriteLine("=================================================");
 result = pOp3->Invoke(3.0);
 Console::WriteLine("=================================================");
 result = pOp4->Invoke(3.0);
 Console::WriteLine("=================================================");
 NumericOp^ pOp6 = dynamic_cast<NumericOp^>(Delegate::Remove(pOp4, pOp5));
 result = pOp6->Invoke(3.0);

 Console::ReadKey();

 Application::Run(gcnew CppForm());
 */
 return 0;
}