2013-05-12 136 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

相关问题