c# - 将事件集中到一行?

标签 c# events

当用户单击按钮时,将激活此事件:

flightWindow.SendAirplaneLand += onAirplaneStartSend; 
flightWindow.SendAirplaneTakeOff += onAirplaneTakeOffSend;
flightWindow.SendAirplaneChangeRoute += onAirplaneChangeRouteSend;

它们都调用不同的方法来将信息添加到列表中:

public void onAirplaneStartSend(object sender, Land e)
    {
        listBoxFlightEvents.Items.Add(e.LandStatus);
    }

    public void onAirplaneTakeOffSend(object sender, TakeOff e)
    {
        listBoxFlightEvents.Items.Add(e.TakeOffStatus);
    }

    public void onAirplaneChangeRouteSend(object sender, ChangeRoute e)
    {
        listBoxFlightEvents.Items.Add(e.ChangeRouteStatus);
    }

我的问题是,我想将所有这些信息添加到一行文本中以添加到列表中,并且我正在寻找一个简单的解决方案,如何做到这一点?

一种方法是让方法返回一个字符串,并将所有返回的字符串值放在一起,然后将其添加到列表中,如下所示:

public string onAirplaneStartSend(object sender, Land e)
    {
        return e.LandStatus;
    }

但他的也许不可能也不方便?

最佳答案

flightWindow.SendAirplaneLand += (s,e) => {
  OnAirplaneStatusChange(e.LandStatus);
};
flightWindow.SendAirplaneTakeOff += (s,e) => {
  OnAirplaneStatusChange(e.TakOffStatus);
};
flightWindow.SendAirplaneChangeRoute += (s,e) => {
  OnAirplaneStatusChange(e.ChangeRouteStatus);
};

private void OnAirplaneStatusChange(string status)
{
  listBoxFlightEvents.Items.Add(status);
}

虽然我仍然不完全确定你要做什么。除非Land , TakeOffChangeRoute都继承了一些共同点(例如)AirplaceEventArgs (以及表示状态的公共(public)属性)您必须单独绑定(bind)它们。最好的情况是使用通用 EventArgs方法,但您需要以某种方式进行转换才能获得 LandStatus , TakeOffStatusChangeRouteStatus值。

我建议:

public class AirplaneEventArgs : EventArgs
{
  public string Status { get; set; }
}
public class TakeOffEventArgs : AirplaneEventArgs
{
  /* other properties */
}
public class LandEventArgs : AirplaneEventArgs
{
  /* other properties */
}
public ChangeRouteEventArgs : AirplaneEventArgs
{
  /* other properties */
}

然后您可以简单地绑定(bind):

flightWindow.SendAirplaneLand += OnAirplaneStatusChange; 
flightWindow.SendAirplaneTakeOff += OnAirplaneStatusChange;
flightWindow.SendAirplaneChangeRoute += OnAirplaneStatusChange;

private void OnAirplaneStatusChange(object sender, AirplaneEventArgs e)
{ 
    // they all now share "Status" proeprty so no need to cast to
    // get "LandStatus" vs. "ChangeRouteStatus" vs. "TakeOffStatus"
    // values.
    listBoxFlightEvents.Items.Add(e.Status);
}

关于c# - 将事件集中到一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11907404/

相关文章:

c# - ASP.NET MVC 中 HTTP 自动重定向到 HTTPS

c# - 从另一个 Web api 调用一个 Web api

c# - 获取异步结果死锁(尽管将 configure await 设置为 false)

c# - Linq to EF .Clear() 不清除

javascript - 避免在 Mootools 中使用匿名函数?

javascript - 在纯 JavaScript 中,什么相当于 "jQuery.on"?

javascript - 使用循环 onclick 更改背景颜色

python - 将组分配给 Pandas 列中的连续 1

c# - 捕获 SQL 连接的信息消息有什么好处?

events - 事件点击 : Varying results with CGEventPost, kCGSessionEventTap, kCGAnnotatedSessionEventTap, CGEventTapPostEvent