在链接课程中提高事件

时间:2011-09-25 06:53:13

标签: events c++-cli

说我有三个类:class1,control1和form1; form1实例化contorl。和control1实例化class1,后者产生一些我需要“绕过”到form1的事件,以实现我已经创建了一个中间函数,如下所示:

public delegate void TestHandler(String^ str);
public ref Class class1
{
    event TestHandler^ TestHappen;
    void someFunction()
    {
        TestHappen("test string");
    }
};

public ref Class control1
{
    event TestHandler^ TestHappen;
    class1^ class1Obj;
    control1()
    {
        class1Obj= gcnew class1();
        class1Obj->TestHappen+= gcnew TestHandler(this,&control1::onTest);  
    }   
    void onTest(String^ str)
    {
        TestHappen(str);
    }
};

public ref Class form1
{
    control1^ control1Obj;
    form1()
    {
        control1Obj= gcenw control1();
        control1Obj->TestHappen+= gcnew TestHandler(this,&form1::onTest);
    }
    void onTest(String^ str)
    {
        //do something with the string...
    }
};

我不想在form1中使用class1,有没有办法删除中间的onTest()函数。

1 个答案:

答案 0 :(得分:3)

是的,如果您使用自定义事件,则可以编写其add-handler和remove-handler函数,以便他们直接从另一个对象的事件中添加和删除委托。

例如:

public ref class control1 // in "ref class", class is lowercase!
{
    class1 class1Obj; // stack-semantics syntax, locks class1Obj lifetime to be same as the containing control1 instance

public:
    event TestHandler^ TestHappen {
        void add(TestHandler^ handler) { class1Obj.TestHappen += handler; }
        void remove(TestHandler^ handler) { class1Obj.TestHappen -= handler; }
    }
};