c++/cli中事件与委托的简单示例

#include "stdafx.h"
using namespace System;
public ref class Server{
public:
	delegate void NewMsgEventHandler(String^ msg);
		static  NewMsgEventHandler^ _ProcessNewMsg;
	static event NewMsgEventHandler^ ProcessNewMsg
	{
		void add(NewMsgEventHandler^ c){ _ProcessNewMsg+=c;}
		void remove(NewMsgEventHandler^ c)
		{
			_ProcessNewMsg-=c;
		}
		void raise(String^ str){
			_ProcessNewMsg->Invoke(str);
		}
	}
	static void Broadcast(String^ msg)
	{
		if (Server::_ProcessNewMsg != nullptr)
		{
			ProcessNewMsg(msg);
		}
	} 
}; 
public ref class Client
{
	String^ clientName;
	/*4*/ void ProcessNewMsg(String^ msg)
	{
		Console::WriteLine("Client {0} received message {1}", clientName, msg);
	}
public:
	Client(String^ clientName)
	{
		this->clientName = clientName;
		/*5*/
		Server::ProcessNewMsg += gcnew Server::NewMsgEventHandler(this,&Client::ProcessNewMsg);
	}
	/*6*/ ~Client()
	{
		Server::ProcessNewMsg -= gcnew Server::NewMsgEventHandler(this,&Client::ProcessNewMsg);
	}
}; 
 
using namespace System;
 class cls
{
public: cls()
	{
 
	}
public:
	int i;
	int j;
};
int main()
{
	String^ str="hello"+"world";
	Server::Broadcast("Message 1");
	Client^ c1 = gcnew Client("A");
	Server::Broadcast("Message 2");
	Client^ c2 = gcnew Client("B");
	Server::Broadcast("Message 3");
	Client^ c3 = gcnew Client("C");
	Server::Broadcast("Message 4");
	c1->~Client();
	Server::Broadcast("Message 5");
	c2->~Client();
	Server::Broadcast("Message 6");
	c3->~Client();
	Server::Broadcast("Message 7");
	Int32^ i=gcnew Int32;
	*i=5;
	Console::WriteLine(Convert::ToString(*i));
 
	cls* cls1=new cls;
	//cls1->i=5;
 
	Console::WriteLine((*cls1).j);
	Console::ReadLine();
} 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值