创建类的句柄财产

发布于 2024-08-31 03:21:43 字数 188 浏览 2 评论 0原文

是否可以为类的属性创建一个句柄(或跟踪句柄)?例如,

System::Windows::Forms::CheckBox^ Box = gcnew System::Windows::Forms::CheckBox()

我想创建 Box 的 Checked 属性的句柄,并使用它来访问和修改该属性。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮生面具三千个 2024-09-07 03:21:43

属性只不过是 set/get 方法的语法糖,据我所知,没有办法捕获对属性的任何类型的引用(我想类似于绑定方法)。

我能想到的最好的解决方法(需要 VS2010)是传递几个 lambda:

auto set = [=](bool b) { Box->Checked = b; };
auto get = [=]() -> bool { return Box->Checked; };

编辑(因为你没有 VS2010):

你当然可以恢复到编写专用类的更巴洛克惯例:

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;
};

如果有人问你 C++ lambda 有什么用处,那么很难跳过这个例子。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文