2013-05-12 68 views
3

我的代碼有什麼問題?無法將類型IAsyncOperation <StorageFile>隱式轉換爲StorageFile

private void BrowseButton_Click(object sender, RoutedEventArgs e) 
    { 
     FileOpenPicker FilePicker = new FileOpenPicker(); 
     FilePicker.FileTypeFilter.Add(".exe"); 
     FilePicker.ViewMode = PickerViewMode.List; 
     FilePicker.SuggestedStartLocation = PickerLocationId.Desktop; 
     // IF I PUT AWAIT HERE V  I GET ANOTHER ERROR¹ 
     StorageFile file = FilePicker.PickSingleFileAsync(); 
     if (file != null) 
     { 
      AppPath.Text = file.Name; 
     } 
     else 
     { 
      AppPath.Text = ""; 
     }   
    } 

它給我這個錯誤:

Cannot implicitly convert type 'Windows.Foundation.IAsyncOperation' to 'Windows.Storage.StorageFile'

如果我加入 '等待',就像評論的代碼,我收到以下錯誤:

¹ The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

代碼源here

回答

5

那麼,你的代碼不編譯的原因直接由編譯器錯誤消息。 FileOpenPicker.PickSingleFileAsync返回IAsyncOperation<StorageFile> - 因此不可以,您無法將該返回值分配給StorageFile變量。在C#中使用IAsyncOperation<>的典型方法是使用await

只能在async方法使用await ......所以你可能想改變你的方法是異步的:

private async void BrowseButton_Click(object sender, RoutedEventArgs e) 
{ 
    ... 
    StorageFile file = await FilePicker.PickSingleFileAsync(); 
    ... 
} 

注意,對於比事件處理程序的其他任何東西,這是更好地使異步方法返回Task而不是void - 使用void的能力實際上只能讓您可以使用異步方法作爲事件處理程序。

如果您還不是很熟悉async/await,那麼您應該在進一步閱讀之前仔細閱讀它 - MSDN "Asynchronous Programming with async and await"頁面可能是一個體面的起點。

+0

現在我明白了,非常感謝!我開始學習C#,而這個異步/等待的東西對我來說真的很新鮮。 您的幫助非常感謝! – gabrieljcs 2013-05-12 22:16:58

相關問題