2012-02-10 57 views
1

这已被窃听我一会儿,我问同事,如果他能做出任何意义,现在我在这里;)PropertyChangedCallback封装

你怎么可以访问控股的私有成员类的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应用程序中使用它:它允许我保留一个变量专用,同时仍然在回调中访问它。
但是,因为它确实感觉不太对劲,所以我不希望它在WPF vNext中“固定”,导致我的应用程序不兼容。

此致敬礼

bab。

回答

4

回调在拥有私有成员的同一个类中定义,这种访问没有任何问题。看起来私人实例成员似乎是“从外部”访问的,但你仍然在同一个班级中似乎很奇怪。

+0

该死的,你每天都会学到一些东西。 2年来,我一直在编程,我从来没有试过访问这样的私人成员。在这里,我认为这是一个依赖属性的珍宝魔法。傻我。谢谢! – 2012-02-10 13:19:16

+0

不客气!如果你想看到*真的很奇怪,那么看看[数组中的类型协变](http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance- in-c-part-two-array-covariance.aspx):D – 2012-02-10 13:22:00

+1

我以前读过那篇文章。好几次,直到我真正了解了xD但是在和前哨物打过仗之后,当谈到我爱的爱情伙伴WPF时,我留意到奇怪。 [博客文章](http://baboon.eu/) – 2012-02-10 13:30:46