Would it be possible to create a handle ( or a tracking handle ) to a class' property ? For instance,
System开发者_开发知识库::Windows::Forms::CheckBox^ Box = gcnew System::Windows::Forms::CheckBox()
I'd like to create a handle to Box's Checked property and use it to access and modify the same.
Properties are little more than syntactic sugar for set/get methods, and there is, AFAIK, no way to capture any kind of reference to one (something akin to a bound Method, I suppose).
The best workaround I can think of, which requires VS2010, is to pass a couple of lambdas around:
auto set = [=](bool b) { Box->Checked = b; };
auto get = [=]() -> bool { return Box->Checked; };
EDIT (since you don't have VS2010):
You can of course revert to the rather more baroque convention of writing a special-purpose class:
public generic<typename T> interface class PropertyProxy
{
property T Field;
};
public ref class CheckBoxChecked : public PropertyProxy<bool>
{
public:
CheckBoxChecked(System::Windows::Forms::CheckBox^ box) : _box(box) { }
property bool Field
{
bool get() { return _box->Checked; };
void set(bool b) { _box->Checked = b; };
}
private:
System::Windows::Forms::CheckBox^ _box;
};
If anyone ever asks you what C++ lambdas are good for, it's hard to go past this example.
精彩评论