这已经困扰我一段时间了,所以我问了一个同事他是否能理解它,现在我来了;)
为什么可以在依赖属性的 PropertyChangedCallback 中访问持有类的私有(private)成员?
让我通过这个例子进一步解释我的意思:
/// <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 应用程序中使用它:它允许我在回调中访问它的同时保持变量私有(private)。
但由于它真的感觉根本不对,我不希望它在 WPF vNext 中被“修复”,从而使我的应用程序不兼容。
最好的问候,
宝贝。
请您参考如下方法:
回调在拥有私有(private)成员的同一个类中定义,这种访问没有错。私有(private)实例成员看似“从外部”访问,但您仍在同一个类中,这似乎很奇怪。
