如何将字符串添加到 Windows 窗体标签?

Kyl*_*yle 2 .net string c++-cli stdstring winforms

我试着这样做:

this->Label1->Text = "blah blah: " + GetSomething();
Run Code Online (Sandbox Code Playgroud)

哪里GetSomething()是返回字符串的函数。

编译器给了我一个错误:

“错误 C2679:二进制 '+':未找到采用 'std::string' 类型的右侧操作数的运算符(或没有可接受的转换)”

string GetSomething()
{
    int id = 0;
    string Blah[] = {"test", "fasf", "hhcb"};

    return Blah[id];
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ray 5

问题是这里至少有两个不同的字符串类在起作用。

WinForms(您显然将其用于 GUI)在任何地方都使用.NETSystem::String。因此该Label.Text属性正在获取/设置 .NETSystem::String对象。

您在问题中说该GetSomething()方法返回一个std::string对象。的std::string类基本上是C ++的内置字符串类型,作为标准库的一部分提供的。

这两个类都很好并且很好地满足了各自的目的,但它们不直接兼容。这就是(第二次尝试的)编译器消息试图告诉您的:

错误 C2664: void System::Windows::Forms::Control::Text::set(System::String ^): 无法将参数 1 从 转换std::basic_string<_Elem,_Traits,_Ax>System::String ^

用简单的英语重写:

错误 C2664:无法将std::string作为参数 1 传递的本机对象转换System::StringControl::Text属性所需的托管对象

事实是,您真的不应该混合使用这两种字符串类型。由于 WinForms 本质上是将其字符串类型强加给您,因此我将对其进行标准化,至少对于与 GUI 交互的任何代码而言。所以如果可能的话,重写GetSomething()方法返回一个System::String对象;例如:

using namespace System;

...

String^ GetSomething()
{
    int id = 0;
    array <String^>^ Blah = gcnew array<String^>{"test", "fasf", "hhcb"};
    return Blah[id];
}

...

// use the return value of GetSomething() directly because the types match
this->Label1->Text = "blah blah: " + GetSomething();
Run Code Online (Sandbox Code Playgroud)

如果这是不可能的(例如,如果这是与您的 GUI 几乎没有关系或根本没有关系的库代码),那么您需要将一种字符串类型显式转换为另一种

#include <string>  // required to use std::string

...

std::string GetSomething()
{
    int id = 0;
    std::string Blah[] = {"test", "fasf", "hhcb"};
    return Blah[id];
}

...

// first convert the return value of GetSomething() to a matching type...
String^ something = gcnew String(GetSomething().c_str());

// ...then use it
this->label1->Text = "blah blah: " + something;
Run Code Online (Sandbox Code Playgroud)