最接近C# 的Event的C++处理

最接近C# EventC++处理

 

嗯,最近搞了一点C++,完成了所谓的C++下的Event,懒得多说看代码

#include "boost/function.hpp"

#include "boost/bind.hpp"

#include "iostream"

 

using namespace boost;

using namespace std;

 

template<typename T>

class Event

{

    bool flag;

public:

    typedef boost::function<T> handle_type;

    handle_type Invoke;

 

    Event():flag(false),Invoke()

    {

 

    }

 

    Event& operator= (const boost::function<T>& rhs)

    {

       this->Invoke = rhs;

       flag = true;

       return *this;

    }

 

    void Clear()

    {

       flag = false;

    }

 

    bool IsNull()

    {

       return !flag;

    }

 

};

这样就完成了Event的宣告。用起来实在是很方便,举个小例子

 

比如这里定义一个窗体类:

class Window

{

public:

    Event<void(int)> ClickEvent;   

 

    void test()

    {

       if(!ClickEvent.IsNull())

       {

           ClickEvent.Invoke(100);

       }

    }

};

 

再搞一个测试的片段

void foo(int x)

{

    cout << "x= " << x <<endl;

}

 

class Foo

{

public:

    void foo(int x)

    {

       cout << "foo:: x= " << x <<endl;

    }

};

 

int _tmain(int argc, _TCHAR* argv[])

{

    Window win;

    Foo f;

    win.ClickEvent = bind(&foo,_1);

    win.test();

   

    win.ClickEvent = bind(&Foo::foo,&f,_1);

    win.test();

 

    win.ClickEvent.Clear();

    win.test();

    return 0;

}

是不是一切都很美妙呢!当然你可以直接使用boost::function,不过会有一个小小的问题,你无法来判断boost::function这个东东是不是一个零值,而且每次调用时需要去写一个判断是不是很烦呢?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
您好!要测试 C++ 生成的 OCX(ActiveX 控件)与 C# 进行交互,您可以按照以下步骤进行操作: 1. 在 C# 项目中添加对 COM 组件的引用: - 在 Visual Studio 中,打开您的 C# 项目。 - 在“解决方案资源管理器”中,右键单击“引用”,然后选择“添加引用”。 - 在弹出的对话框中,选择“浏览”选项卡。 - 浏览到您的 C++ 生成的 OCX 文件(通常具有 .ocx 扩展名),选择并单击“确定”。 - 确保已选中 OCX 的引用,然后单击“确定”。 2. 使用 OCX 控件: - 在您的 C# 代码中,使用 `using` 关键字导入 OCX 控件的命名空间。 - 创建 OCX 控件的实例,并使用其提供的方法、属性和事件。 下面是一个简单的示例代码,演示如何在 C# 中使用 OCX 控件: ```csharp using System; using MyOcxNamespace; // 替换为您的 OCX 控件的命名空间 class Program { static void Main(string[] args) { MyOcxClass ocx = new MyOcxClass(); // 替换为您的 OCX 类名 // 调用 OCX 控件提供的方法 ocx.Method1(); // 设置和获取 OCX 控件的属性 ocx.Property1 = "Hello"; string value = ocx.Property1; // 注册 OCX 控件的事件处理程序 ocx.Event1 += OcxEvent1Handler; } // OCX 事件处理程序 static void OcxEvent1Handler() { Console.WriteLine("OCX Event 1 occurred!"); } } ``` 请注意,您需要替换示例代码中的命名空间、类名、方法、属性和事件为您实际使用的 OCX 控件的信息。 希望这可以帮助到您!如果您有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BlueDog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值