我有一个Getter和一个Setter for a view。 目前我正在传递一个字符串并检查它。 并相应地设置数据。由于我有大约50多种混合小部件,因此它变得笨拙。
您能否推荐比我目前使用的解决方案更好的解决方案。
Setter代码
void wxfbIntegrationFrame::SetWidgetValue(wxString widget, wxString data)
{
if (widget.compare("hours") == 0) { hours->SetValue(data); }
else if (widget.compare("flowrateon") == 0) { flowrateon->SetValue(data); }
else if (widget.compare("pressureon") == 0) { pressureon->SetValue(data); }
else if (widget.compare("flowrateoff") == 0) { flowrateoff->SetValue(data); }
else if (widget.compare("pressureoff") == 0) { pressureoff->SetValue(data); }
else if (widget.compare("surveynumber") == 0) { surveynumber->SetValue(data); }
else if (widget.compare("warninglabel") == 0) { warninglabel->SetLabelText(data); }
}
Getter代码
int wxfbIntegrationFrame::GetWidgetValue(wxString widget)
{
long val;
if (widget.compare("surveyvalue") == 0)
{
return surveynumber->GetValue();
}
else if (widget.compare("xoffset") == 0)
{
wxString data = apply_offset_x->GetValue();
data.ToLong(&val);
return val;
}
else if (widget.compare("yoffset") == 0)
{
wxString data = apply_offset_y->GetValue();
data.ToLong(&val);
return val;
}
else if (widget.compare("countdowntimer") == 0)
{
return timercount->GetValue();
}
else if (widget.compare("sensornumber") == 0)
{
wxString data = sensornumber->GetValue();
data.ToLong(&val);
return val;
}
else if (widget.compare("temperatureselection") == 0)
{
return TempSelection->GetValue();
}
}
答案 0 :(得分:5)
通过使用unordered_map
您只需在构造函数中初始化它:
#include <unordered_map>
#include <string>
#include <exception>
#include <functional>
class wxfbIntegrationFrame
{
public:
wxfbIntegrationFrame()
{
_setters["hours"] = [this](const wxString &data) { this->hours->SetValue(data); };
_setters["flowrateon"] = [this](const wxString &data) { this->flowrateon->SetValue(data); };
...
_getters["hours"] = [this](int &data){ data = this->hours->GetValue();};
}
void SetWidgetValue(const wxString &widget, const wxString &data)
{
try
{
_setters.at(widget)(data);
}
catch (const std::out_of_range &err)
{
whatever you want to do
}
}
int GetWidgetValue(const wxString &widget)
{
int data;
try
{
_getters.at(widget)(data);
return data;
}
catch (const std::out_of_range &err)
{
whatever you want to do
}
}
private:
std::unordered_map<std::string, std::function<void (const wxString &)> > _setters;
std::unordered_map<std::string, std::function<void (int &)> > _getters;
}