2010-11-24 72 views
4
private void GeoCode_Method1(string myaddress, int waypointIndex, string callingUser) 
{   
    GCService.GeocodeCompleted += new EventHandler<NSpace.GCService.GeocodeCompletedEventArgs>(GeoCode_Method1_GeocodeCompleted); 
    GCService.GeocodeAsync(request, waypointIndex); 
} 

void GeoCode_Method1_GeocodeCompleted(object sender, NSpace.GCService.GeocodeCompletedEventArgs e) 
{ 
    //***QUESTION: how do I access variable "callinguser" from GeoCode_Method1 in this method?? 
} 

当我打电话到GeoCode_Method1我在“callinguser”字符串变量发送,我想访问这个在GeoCode_Method1_GeocodeCompleted(当异步GeoCodingAsync调用完成触发)。我该怎么做呢?传递的异步附加变量完成事件处理

回答

4

最简单的方法是使用C#lambda表达式作为事件处理函数。这个lambda表达式可以调用GeoCode_Method1_GeocodeCompleted方法并传递callinguser参数。

GCService.GeocodeCompleted += 
    (sender, e) => GeoCode_Method1_GeocodeCompleted(callinguser, sender, e); 
GCService.GeocodeAsync(request, waypointIndex); 

void GeoCode_Method1_GeocodeCompleted(
    string callingUser, 
    object sender, 
    Space.GCService.GeocodeCompletedEventArgs e) { 
    //***QUESTION: how do i access variable "callinguser" from GeoCode_Method1 in this method?? 
} 
+0

谢谢大家!现在明白了。 – Simba 2010-11-28 03:58:07

0

您应该创建一个lambda expression

private void GeoCode_Method1(string myaddress, int waypointIndex, string callingUser) 
{   
    GCService.GeocodeCompleted += (sender, e) => { 
     MessageBox.Show(callingUser); 
    }; 
    GCService.GeocodeAsync(request, waypointIndex); 
} 

Lambda表达式可以访问所有的外部方法变量和参数。 (这被称为closure

lambda表达式的sendere参数是基于它被用作的委托类型隐含类型的。

1

理想的GCService将有处理,对你(应该如果正确遵守的异步事件模式)的方式,但如果它不存在使用C#闭包,虽然这是一个小的方式复杂。

你会这么做,如下所示 - 在我的示例中,我已经展示了如何确保GeocodeCompleted事件处理程序在事件完成时取消订阅。

private void GeoCode_Method1(string myaddress, int waypointIndex, string callingUser) 
{  
    // declare the eventHandler before assignment so that it's accessible in the 
    // lambda function  
    EventHandler<NSpace.GCService.GeocodeCompletedEventArgs> eventHandler = null; 
    eventHandler = (sender, eventArgs) => HandleGeocodeCompleted(sender, eventArgs, callingUser, eventHandler); 
    GCService.GeocodeCompleted += eventHandler; 
    GCService.GeocodeAsync(request, waypointIndex); 
} 

void HandleGeocodeCompleted(object sender, NSpace.GCService.GeocodeCompletedEventArgs e, string callingUser, EventHandler<NSpace.GCService.GeocodeCompletedEventArgs> eventHandler) 
{ 
    GCService.GeocodeCompleted -= eventHandler; 
    // use callingUser here 
} 
+0

因为如果你不编译器会在第6行给你一个错误,使用未分配的局部变量'eventHandler' – 2010-11-24 17:52:52