开发者

raising events in chaining classes

say I have three classes: class1, control1 and form1; form1 instantiate contorl. and control1 instantiate class1, the later produces some event that I need to 'bypass' to form1, to achieve that I have made an intermediate function as shown below:

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()
    {
        clas开发者_如何学Pythons1Obj= 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...
    }
};

I don't want to use class1 in form1, are there a way to remove the intermediate onTest() function.


Yes, if you use a custom event, you can write its add-handler and remove-handler functions so that they add and remove the delegate directly from another object's event.

For example:

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; }
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜