简体   繁体   中英

how to assign same event to different objects?

Im usying a component that have an OnData event. I want to create 100 object from this component with almost same OnData event.

my code is like this:

        Tcp[] arrTcp = new Tcp[100];

        for(int i=0; i<100; i++)
        {
            arrTcp[i] = new Tcp();

            arrTcp[i].Data += tcp1_Data;
        }

but OnData event is a bit diffrent in each tcp object.

    void tcp1_Data(object sender, Dart.Sockets.DataEventArgs e)
    {

        // all code are same except this part :

        if(tcp1)
            Console.WriteLine("tcp1");

        if(tcp2)
            Console.WriteLine("tcp2");

        .....
    }

I dont want to write 100 events... any idea?

for more information: tcp1_Data will fire by multi threading ...

I would do something like this:

var arrTcp = new Tcp[100];

var specificCode = new Dictionary<int, Action<int, Tcp>>()
{
    { 0, (index, tcp) => Console.WriteLine("tcp1") },
    { 1, (index, tcp) => Console.WriteLine("tcp2") },
    // ...
    { 99, (index, tcp) => Console.WriteLine("tcp100") },
};

for (var i = 0; i < 100; i++)
{
    arrTcp[i] = new Tcp();

    var index = i;
    arrTcp[i].Data += (s, e) =>
    {
        // all code are same except for :
        specificCode[index](index, arrTcp[index]);
    };
}

Now, this isn't a great improvement except that it probably makes the code slightly more maintainable. However, depending on the complexity in the code in the specificCode dictionary, this might even be worse to maintain.

I suspect that the problem you are trying to solve here isn't actually about writing custom code for each event handler. I think you probably have an underlying issue that you thought could be solved in this way. If you could post another question with your underlying need I think we could help you more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM