问题描述
我的代码到底怎么了?
私有无效的BrowseButton_Click(对象发送者,RoutedEventArgs e){FileOpenPicker FilePicker =新的FileOpenPicker();FilePicker.FileTypeFilter.Add(.exe");FilePicker.ViewMode = PickerViewMode.List;FilePicker.SuggestedStartLocation = PickerLocationId.Desktop;//如果我在这里等我又遇到其他错误¹StorageFile文件= FilePicker.PickSingleFileAsync();如果(文件!= null){AppPath.Text = file.Name;}别的{AppPath.Text =";}}
它给了我这个错误:
如果我添加"await"(如在代码中注释),则会出现以下错误:
代码源此处
好吧,编译器错误消息非常直接地解释了代码未编译的原因. FileOpenPicker.PickSingleFileAsync
返回 IAsyncOperation< StorageFile>
-因此,不能,您不能将该返回值分配给 StorageFile
变量.在C#中使用 IAsyncOperation<>
的典型方法是使用 await
.
您只能在 async
方法中使用 await
...因此,您可能希望将方法更改为异步方法:
私有异步void BrowseButton_Click(对象发送者,RoutedEventArgs e){...StorageFile文件=等待FilePicker.PickSingleFileAsync();...}
请注意,对于事件处理程序以外的其他任何东西,最好使异步方法返回 Task
而不是 void
-使用 void
实际上只是这样,因此您可以使用异步方法作为事件处理程序.
如果您还不太熟悉 async
/ await
,则应该在继续操作之前先阅读一下- MSDN使用异步和等待进行异步编程" 页可能是一个不错的起点.>
What the hell is wrong with my code?
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 = "";
}
}
It gives me this error:
And if I add the 'await', like commented on the code, I get the following error:
Code source here
Well, the reason your code doesn't compile is explained pretty directly by the compiler error message. FileOpenPicker.PickSingleFileAsync
returns an IAsyncOperation<StorageFile>
- so no, you can't assign that return value to a StorageFile
variable. The typical way of using IAsyncOperation<>
in C# is with await
.
You can only use await
in async
methods... so you probably want to change your method to be asynchronous:
private async void BrowseButton_Click(object sender, RoutedEventArgs e)
{
...
StorageFile file = await FilePicker.PickSingleFileAsync();
...
}
Note that for anything other than event handlers, it's better to make an async method return Task
rather than void
- the ability to use void
is really only so you can use an async method as an event handler.
If you're not really familiar with async
/await
yet, you should probably read up on it before you go any further - the MSDN "Asynchronous Programming with async and await" page is probably a decent starting point.
这篇关于无法隐式转换类型IAsyncOperation< StorageFile>.到StorageFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!