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

103 篇文章 0 订阅
53 篇文章 1 订阅

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,但你可以查看其他构造函数来查看你所有可用的选项。

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0x0007

可不可奖励我吃只毛嘴鸡 馋😋

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值