Setting the contents of a Windows Runtime Vector from C++/WinRT in one call - The Old New Thing (microsoft.com)https://devblogs.microsoft.com/oldnewthing/20240524-00/?p=109804Raymond Chen 2024年05月24日
在一次调用中设置 C++/WinRT 中 Windows 运行时向量的元素
我们之前看到,你可以在一个 std::vector
中构建 Windows 运行时 IVector
的初始内容(这通常更方便,性能也更好),然后将其转换为 Windows 运行时 IVector
作为最后一步。或者你可以完全不使用显式的 std::vector
来创建 Windows 运行时 IVector
。
但如果有人给了你一个现有的 Windows 运行时 IVector
,你想要用新内容覆盖其当前内容怎么办?这在 Windows 运行时的许多部分都会发生,例如 FileOpenPicker
,它给你一个 FileTypeFilter
,你可以用你想要过滤的文件类型来填充它。你不能提供你自己的 IVector
;你必须填充现有的。
天真的方法是先清空向量,然后逐个用项目填充它:
namespace winrt
{
using namespace winrt::Windows::Storage::Pickers;
}
winrt::FileOpenPicker CreatePickerForSupportedImages()
{
winrt::FileOpenPicker picker;
auto filter = picker.FileTypeFilter();
filter.Clear();
filter.Append(L".jpg");
filter.Append(L".png");
filter.Append(L".bmp");
filter.Append(L".gif");
filter.Append(L".tif");
return picker;
}
但有一种一站式的方法可以做到这一点:ReplaceAll
方法。
winrt::FileOpenPicker CreatePickerForSupportedImages()
{
winrt::FileOpenPicker picker;
auto filter = picker.FileTypeFilter();
filter.ReplaceAll({ L".jpg", L".png", L".bmp", L".gif", L".tif" });
return picker;
}
ReplaceAll
方法用你提供的值替换向量的整个内容。你可以将其视为 Clear
和 Append
的组合,但所有操作都是一次性完成的。
ReplaceAll
方法接受一个 winrt::array_view
,所以你可以通过 array_view
构造的任何东西来传递。在这个例子中,我们使用了 initializer_list
,但你可以查看其他构造函数来查看你所有可用的选项。