【发布时间】:2019-10-10 14:28:45
【问题描述】:
在面向对象编程中,对象以最高权限管理自己的属性,并通过它们的正式接口与其他对象进行通信。这就是封装原理。对于普通属性,有 Getters/Setters。
对象可以对 setter 中的允许值施加约束。例如,此类不允许 Age 属性的值小于 0 或大于 150:
Class person
{
public string Name {get; set;}
private int age;
public int Age
{
get => age;
set
{
if (value<0) throw new ArgumentException("no one can have negative age! you ape!");
if (value>150) throw new ArgumentException("master Yoda's profile
should be loaded in the Galactic Empire database (currently developed by Mocrisoft)");
age = value;
}
}
}
现在,假设 Person 类是一个 DependencyObject(它继承自 DependencyObject),我想公开一个 DepedencyProperty,并让对象的这个属性成为其他对象属性的从属。所以,Age 属性看起来像......:
public int Age
{
get { return (int)GetValue(AgeProperty); }
set { SetValue(AgeProperty, value); }
}
// Using a DependencyProperty as the backing store for Age. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AgeProperty =
DependencyProperty.Register("Age", typeof(int), typeof(Person), new PropertyMetadata(0, callback));
private static void callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// inspect changed triggered by other object ;
}
使用这种方法,我可以在回调方法中检查正在发生的事情,我可以同时检查旧值和新值。但是这样我只能检查新值,但不能限制或禁止新值。
如何对属性的可能值施加限制?
【问题讨论】: