PropertyChangedCallback encapsulation



这件事困扰了我一段时间,所以我问一位同事他是否能理解,现在我来了;)

为什么你可以在依赖属性的PropertyChangedCallback中访问持有类的私有成员
让我通过这个例子进一步解释一下我的意思:

 /// <summary>
    /// Interaction logic for ZeControl.xaml
    /// </summary>
    public partial class ZeControl : UserControl
    {
        public ZeControl()
        {
            InitializeComponent();
        }
        private bool m_Trololo; //Please note that this field is PRIVATE!
        #region Text
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }
        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(ZeControl), new UIPropertyMetadata(
                new PropertyChangedCallback((dpo, dpce) =>
                    {
                        ((ZeControl)dpo).m_Trololo = true; //How the hell?
                        //this.m_Trololo <-- would not compile, the callback is static.
                    })));
        #endregion
    }

这不是在破坏封装吗?它是如何编译的

我之所以这么问,主要是因为我在WPF应用程序中使用了它:它允许我在回调中访问变量的同时保持变量的私有性
但由于感觉真的一点都不对劲,我不希望在WPFvNext中"修复"这一问题,使我的应用程序不兼容。

致问候,

bab。

回调是在拥有私有成员的同一个类中定义的,这种访问没有错。一个私有实例成员似乎是"从外部"访问的,但您仍然在同一个类中,这可能看起来很奇怪。

最新更新