翻译《The Old New Thing》- Setting the contents of a Windows Runtime Vector from C++/WinRT in one call

Setting the contents of a Windows Runtime Vector from C++/WinRT in one call - The Old New Thing (microsoft.com)icon-default.png?t=N7T8https://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 方法用你提供的值替换向量的整个内容。你可以将其视为 ClearAppend 的组合,但所有操作都是一次性完成的。

        ReplaceAll 方法接受一个 winrt::array_view,所以你可以通过 array_view 构造的任何东西来传递。在这个例子中,我们使用了 initializer_list,但你可以查看其他构造函数来查看你所有可用的选项。

相关推荐

  1. 翻译prompt

    2024-06-17 05:42:02       10 阅读
  2. 翻译翻译!AI是什么?

    2024-06-17 05:42:02       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-17 05:42:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-17 05:42:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-17 05:42:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-17 05:42:02       18 阅读

热门阅读

  1. 【软件安装12】CloudCompare点云工具安装 Ubuntu18.04

    2024-06-17 05:42:02       9 阅读
  2. Linux下git用http连接时免输密码方法

    2024-06-17 05:42:02       8 阅读
  3. git 常用的命令

    2024-06-17 05:42:02       8 阅读
  4. 【多线程实例】

    2024-06-17 05:42:02       5 阅读
  5. Jupyter Notebook 入门教程

    2024-06-17 05:42:02       7 阅读
  6. 字符串数组——传递文本的不同方法实例

    2024-06-17 05:42:02       6 阅读
  7. Linux更改默认python版本

    2024-06-17 05:42:02       5 阅读
  8. 力扣上的经典问题:接雨水

    2024-06-17 05:42:02       6 阅读
  9. C++文本文件的读与写

    2024-06-17 05:42:02       6 阅读
  10. C++回溯算法

    2024-06-17 05:42:02       6 阅读
  11. 杂谈-Android和Ios的对比

    2024-06-17 05:42:02       10 阅读