C# 将额外的参数传递给事件

本文关键字:参数传递 事件 | 更新日期: 2023-09-27 17:57:04

我想向事件传递三个额外的参数:

geocodeService.GeocodeCompleted += new EventHandler<GeocodeService.GeocodeCompletedEventArgs>(geocodeService_GeocodeCompleted);

参数为

  • int id
  • string color
  • double heading

    private void Geocode(string strAddress, int waypointIndex, int id, string color, double heading)
    {
    
        // Create the service variable and set the callback method using the GeocodeCompleted property.
        GeocodeService.GeocodeServiceClient geocodeService = new GeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
        // NEED TO PASS id, color, heading TO THIS EVENT HANDLER
        geocodeService.GeocodeCompleted += new EventHandler<GeocodeService.GeocodeCompletedEventArgs>(geocodeService_GeocodeCompleted);
        GeocodeService.GeocodeRequest geocodeRequest = new GeocodeService.GeocodeRequest();
        geocodeRequest.Credentials = new Credentials();
        geocodeRequest.Credentials.ApplicationId = ((ApplicationIdCredentialsProvider)BingMap.CredentialsProvider).ApplicationId;
        geocodeRequest.Query = strAddress;
        geocodeService.GeocodeAsync(geocodeRequest, waypointIndex);
    }
    
    private void geocodeService_GeocodeCompleted(object sender, GeocodeService.GeocodeCompletedEventArgs e)
    {
        GeocodeResult result = null;
        if (e.Result.Results.Count > 0)
        {
            result = e.Result.Results[0];
            if (result != null)
            {
                // this.ShowMarker(result);
                this.ShowShip(result);
    
            }
        }
    }
    

C# 将额外的参数传递给事件

看起来GeocodeCompletedEventArgs扩展AsyncCompletedEventArgs. AsyncCompletedEventArgs具有属性 UserState,可用于存储异步事件的状态信息。此状态通常作为参数传递给引发事件的方法。

有关详细信息,请参阅此问题:必应地理编码服务用户作为自定义附加参数的状态用法

可以扩展GeocodeService.GeocodeServiceClient添加这些属性,然后在事件方法中使用sender参数geocodeService_GeocodeCompleted:

var service = (GeocodeService.GeocodeServiceClient) sender;

快速和肮脏(恕我直言)版本是使用 lambda 表达式:

将参数传递给事件处理程序