一个点对象:
public class Point
{
public Point(){ }
public Point(double X, double Y)
{
this.X = X;
this.Y = Y;
}
public double X;
public double Y;
}
一个用到点对象的部分
Point _point;
Point TestPoint
{
get
{
return _point;
}
set
{
_point = value;
Console.WriteLine("修改了TestPoint");
//从这开始要执行很多操作
}
}
执行的代码:
void Main()
{
Console.WriteLine("第一次修改TestPoint");
TestPoint = new Point();
Console.WriteLine("第二次修改TestPoint");
TestPoint.X = 1;
}
输出结果为:
第一次修改TestPoint
修改了TestPoint
第二次修改TestPoint
这怎么办?第二次修改后没有触发set访问器
我需要修改对象的属性时等同于修改了这个对象,有解决每次都要像这样 ↓ 来触发set访问器的方法吗?
Point pt = TestPoint;
pt.X = 1;
TestPoint = pt;
问题已解决
解决方案:
interface IFather
{
List<IFather> Fathers { get; set; }
void ChildsUpdated();
}
class Point : IFather
{
double _x;
double X
{
get
{
return _x;
}
set
{
foreach(IFather father in Fathers) father.ChildChanged();
_x = value;
}
}
List<IFather> _fathers = new List<IFather>{ };
public List<IFather> Fathers
{
get{ return _fathers;}
set{ _father = value;
}
void ChildChanged() { }
}
class B : IFather
{
void AFunction() //对象中的一个方法
{
Point point = new Point(1, 2, this)
point.X = 3; //这里将通过ChlidChanged()方法代替未触发的访问器
}
List<IFather> _fathers = new List<IFather>{ };
public List<IFather> Fathers
{
get{ return _fathers;}
set{ _father = value;
}
void ChlidChanged()
{
//从这里开始做与未被触发的访问器相同的操作
}
}
上面代码是简写的,可能有错误,比如public/private未清楚标注,CSDN的网页输入框太难用了。