[英]How to subscribe to multiple events
我有一個具有屬性的用戶組UserGroup
: User
對象列表。 每個User
object 都會引發特定事件。 我希望能夠處理來自UserGroup
中所有Users
的這個事件。
例如:
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;
}
}
代碼中的這兩個“TODO”就是我要找的。
如何捕獲一個可以由存儲在一個列表中的多個對象引發的事件?
您可以通過非常簡單的方法為每個User
object 訂閱事件:
public void AddUser(IUser user)
{
user.MatchCompleted += OnMatchCompleted; // subscribed event for each user
Users.Add(user);
}
您的活動將如下所示:
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
}
現在,當我們為每個Users
訂閱時,將為用戶集合中的每個用戶調用OnMatchCompleted
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.