一个点对象:
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的网页输入框太难用了。
上面set只是针对TestPoint对象本身,并不是针对它的某个属性,如果是针对属性可以这样
其实这样就行了
public class Point
{
private double _x;
private double _y;
public Point(){ }
public Point(double X, double Y)
{
this.X = X;
this.Y = Y;
}
public double X
{
get {return this._x;}
set
{
this._x=value;
Console.WriteLine("修改了X");
}
}
public double Y
{
get {return this._y;}
set
{
this._y=value;
Console.WriteLine("修改了Y");
}
}
}
用在类本身的那个set可以不要了
你可以把Point定义成不变的。
class Point
{
public int X { get; init; }
public int Y { get; init; }
public Point(int a, int b) { X = a; Y = b; }
}
不允许单个修改
只能
TestPoint = new Point(x, TestPoint.Y);