简体   繁体   English

如何将同一事件分配给不同的对象?

[英]how to assign same event to different objects?

Im usying a component that have an OnData event. 我正在使用具有OnData事件的组件。 I want to create 100 object from this component with almost same OnData event. 我想用几乎相同的OnData事件从此组件创建100个对象。

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. 但是OnData事件在每个tcp对象中有所不同。

    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? 我不想写100个事件...任何想法吗?

for more information: tcp1_Data will fire by multi threading ... 有关更多信息:tcp1_Data将通过多线程触发...

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. 但是,根据specificCode词典中代码的复杂性,维护起来可能更糟。

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. 如果您可以提出另一个与您的基本需求有关的问题,我想我们可以为您提供更多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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