是否可以选择定义一个文本并在以后不将其作为字符串或任何东西使用,而只是作为函数的一部分但能够在程序中间重新定义它(不是发生在预处理器中,而是发生在运行时)?例如,我在 C++ Windows 窗体中有以下代码:
private: System::Void ps1_GotFocus(System::Object^ sender, System::EventArgs^ e)
{
if(this->ps1->Text == L"/ Your text here /") this->ps1->Text = L"";
this->ps1->ForeColor = System::Drawing::Color::FromName( "Black" );
}
private: System::Void ps2_GotFocus(System::Object^ sender, System::EventArgs^ e)
{
if(this->ps1->Text == L"/ Your text here /") this->ps1->Text = L"";
this->ps2->ForeColor = System::Drawing::Color::FromName( "Black" );
}
ps1
和 ps2
是 TextBoxes,我用它来显示一个灰色 '你的文本here' 字符串,当在准备输入的文本框中单击时(当 TB GotFocus
时)清除文本并使输入黑色。考虑到我有 9 个这样的文本框,是否可以用更少的代码来实现所有这些?我尝试使用 #define ps ps1
和全局 ps_GetFocus()
方法在使用该 ps 的所有内容之外使用相同的代码,但如您所知,#define
是在预处理器中完成的,最后一个定义 (ps ps9
) 甚至在程序启动之前就已定义。
有没有办法在运行时定义非范围文本?
最佳答案
只需为所有文本框使用一个通用的 ps_GotFocus
函数,并使用 sender
(您必须先将其转换为适当的类型,不确定如何在 .Net C++ 中使用那个奇怪的 ^
东西,也许 dynamic_cast
会起作用?)而不是各种 ps
对象。
类似的东西:
private: System::Void ps_GotFocus(System::Object^ sender, System::EventArgs^ e)
{
TypeForYourTextBox^ the_sender = dynamic_cast<TypeForYourTextBox^>(sender);
// I'm unsure about the previous line but you get the idea
// You may also want to check that the cast succeeded, ie. the_sender is not null
if (the_sender->Text == L"/ Your text here /") the_sender->Text = L"";
the_sender->ForeColor = System::Drawing::Color::FromName("Black");
}
关于c++ - 在运行时 C++ 定义非作用域文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16179428/