2015-04-04 71 views
0

我正在开发一个Windows Phone应用程序,并且我陷入了一部分。我的项目是在C#/ xaml - VS2013。从Web API返回字符串DownloadCompleteAsync

问题: 我有一个listpicker(名称 - UserPicker),这是所有用户的名称列表。现在我想从该用户名的数据库中获取用户ID。我已经实现了Web Api,我正在使用Json进行反序列化。 但我无法从DownloadCompleted事件返回字符串。

代码:

string usid = ""; 

     selecteduser = (string)UserPicker.SelectedItem; 
     string uri = "http://localhost:1361/api/user"; 
     WebClient client = new WebClient(); 
     client.Headers["Accept"] = "application/json"; 
     client.DownloadStringAsync(new Uri(uri)); 
     //client.DownloadStringCompleted += client_DownloadStringCompleted; 
     client.DownloadStringCompleted += (s1, e1) => 
     { 
      //var data = JsonConvert.DeserializeObject<Chore[]>(e1.Result.ToString()); 
      //MessageBox.Show(data.ToString()); 
      var user = JsonConvert.DeserializeObject<User[]>(e1.Result.ToString()); 
      foreach (User u in user) 
      { 
       if (u.UName == selecteduser) 
       { 
        usid = u.UserID; 

       } 
       //result.Add(c); 

       return usid; 
      } 
      //return usid 
     }; 

我想返回所选用户的用户ID。但它给我的错误。

由于“System.Net.DownloadStringCompletedEventHandler”返回空隙,返回关键字必须不能跟一个对象表达式

无法转换lambda表达式委托类型“System.Net.DownloadStringCompletedEventHandler”,因为一些返回类型的块不隐式转换为委托返回类型

回答

1

如果选中的DownloadStringCompletedEventHandler源代码,你会看到,它就是这样实现的:

public delegate void DownloadStringCompletedEventHandler(
    object sender, DownloadStringCompletedEventArgs e); 

这意味着你不能从它返回任何数据。您可能有一些方法可以对选定的用户标识进行操作。您将需要从事件处理程序调用此方法。因此,如果这种方法被命名为HandleSelectedUserId,那么代码可能看起来像:

client.DownloadStringCompleted += (sender, e) => 
{ 
    string selectedUserId = null; 
    var users = JsonConvert.DeserializeObject<User[]>(e.Result.ToString()); 
    foreach (User user in users) 
    { 
     if (user.UName == selecteduser) 
     { 
      selectedUserId = user.UserID; 
      break; 
     } 
    } 

    HandleSelectedUserId(selectedUserId); 
}; 
client.DownloadStringAsync(new Uri("http://some.url")); 

这也是添加事件处理程序DownloadStringCompleted事件调用DownloadStringAsync方法之前是个好主意。