2015-04-04 74 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方法之前是個好主意。