简体   繁体   English

如何订阅多个事件

[英]How to subscribe to multiple events

I have a UserGroup object that has a property: List of User objects.我有一个具有属性的用户组UserGroupUser对象列表。 Each User object raises particular event.每个User object 都会引发特定事件。 I want to be able to handle this event from all Users in UserGroup .我希望能够处理来自UserGroup中所有Users的这个事件。

For example:例如:

public abstract class User : IUser
{
    public event EventHandler<MatchCompletedEventArgs> MatchCompleted;

    public bool Match(Job job)
    {
        bool result = UserMatch(job);

        EventHandler<MatchCompletedEventArgs> handler = MatchCompleted;
        handler?.Invoke(this, new MatchCompletedEventArgs(result));

        return result;
    }

    protected abstract bool UserMatch(Job job);
}


public class UserGroup
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<IUser> Users { get; set; }

    public UserGroup(int id, string name)
    {
        Id = id;
        Name = name;
        Users = new List<IUser>();
    }

    public void AddUser(IUser user)
    {
        // TODO:
        // In here I want to subscribe to user.MatchCompleted event 
        // Eventually I want to be able to handle MatchCompleted event in all users in the list

        Users.Add(user);
    }

    public void OnMatchCompleted()
    {
        // TODO:
        // Whenever, any of the users throws MatchCompleted completed event I need to store complex informations about the Match process,
        // Ideally in one place, like this function.
    }

    public bool Match(Job job)
    {
        // Match will return TRUE only if all users will match it
        foreach (var user in Users)
        {
            if (!user.Match(job)) return false;
        }
        return true;
    }
}

These two "TODO" in the code is what I'm looking for.代码中的这两个“TODO”就是我要找的。

How can I catch an event that can be raised by multiple objects stored in one list?如何捕获一个可以由存储在一个列表中的多个对象引发的事件?

You can subcribe to the event for each User object in the method which is pretty straightforward:您可以通过非常简单的方法为每个User object 订阅事件:

public void AddUser(IUser user)
{
    user.MatchCompleted  += OnMatchCompleted; // subscribed event for each user       
    Users.Add(user);
}

and your event would look like:您的活动将如下所示:

public void OnMatchCompleted(object sender,MatchCompletedEventArgs e)
{   
    User user = sender as User;   // will work fine
    IUser iUser = sender as IUser; // this will also work

   // now you can use user information
   // write your complex logic here
}

Now this way OnMatchCompleted will be called for every user in the collection of Users as we subscribed for each of them.现在,当我们为每个Users订阅时,将为用户集合中的每个用户调用OnMatchCompleted

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

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