c# – 无法将IAsyncOperation类型隐式转换为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’
如果我添加’await’,就像在代码上发表评论一样,我收到以下错误:
¹ 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
解决方法:
好吧,编译错误消息直接解释了代码无法编译的原因. FileOpenPicker.PickSingleFileAsync
返回IAsyncOperation< StorageFile> – 所以不,您不能将该返回值分配给StorageFile变量.使用IAsyncOperation<>的典型方法在C#等待.
您只能在异步方法中使用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”页面可能是一个不错的起点.
标签:c,async-await,microsoft-metro,filepicker,storagefile 来源: https://codeday.me/bug/20190620/1244076.html