C++/CX:Platform::String与std::wstring的区别

3

看起来C++/CX没有StringBuilder类或其等价物,所以我想我们需要使用STL来做到这一点?

这是我第一个C++/CX应用程序。用户在TextBox中输入一些文本,然后点击ENTER按钮,文本被附加到名为"console"的TextBlock中。这段代码确实可以工作,但最佳实践是什么呢?

public ref class MainPage sealed
{
public:
    MainPage();

protected:
    virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
    std::wstring _commandLine;
    std::wstring _consoleText;
    void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
};

...

void HelloConsole::MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    this->_commandLine = this->InputLine->Text->Data();
    this->_commandLine.append(L"\n");
    this->_consoleText += this->_commandLine;
    this->InputLine->Text = "";
    this->OutputConsole->Text = ref new Platform::String(_consoleText.c_str());
}
1个回答

5
似乎C++/CX没有StringBuilder类或等效类,因此我认为我们应该使用STL?是的,在一般情况下,您应该优先使用C++类型来编写C++代码。仅在必要时(例如在ABI边界或组件边界传递数据时)使用Windows运行时类型(如Platform::String)。您代码片段中的字符串处理看起来很好--将其复制到std::wstring进行修改是合理的。

这肯定比起原生的C字符串和BSTR,甚至是MFC和ATL的CStrings和CComBSTRs更先进。终于可以使用与全世界相同的API,感觉让人耳目一新。 - Paul Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接