C# 如何在变量更改时自动调用函数?
我有一个由变量成员和函数成员组成的类。变量成员偶尔会更改。我希望在变量更改时自动调用该函数。换句话说,如何将变量绑定到类中C# 如何在变量更改时自动调用函数?,c#,class,function-call,C#,Class,Function Call,我有一个由变量成员和函数成员组成的类。变量成员偶尔会更改。我希望在变量更改时自动调用该函数。换句话说,如何将变量绑定到类中 class line { double x, y; // The poition of the lind end. The line starts at the origin (0,0) double l; // The length of the line void length() { l = Math.sqrt(x*x+y*y);
class line
{
double x, y; // The poition of the lind end. The line starts at the origin (0,0)
double l; // The length of the line
void length()
{
l = Math.sqrt(x*x+y*y);
}
}
在上面的示例中,我需要在x和y发生变化时更新长度。将变量设置为属性,然后将函数设置为set accesor
class line
{
double _x, _y;
double x
{
get { return _x; }
set
{
_x = value;
length();
}
}
double y
{
get { return _y; }
set
{
_y = value;
length();
}
}
double l; // The length of the line
void length()
{
l = Math.Sqrt(_x * _x + _y * _y);
}
}
你可以选择你的财产
int x
int X {
get { return x; }
set { x = value; YouMethod();}
}
如果定义了属性,则可以在类上生成X和Y,然后生成一个只读属性L,该属性由以下值计算:
public class Line //class names should be Capitalized
{
public double X{ get; set; } //prop names should be Capitalized
public double Y{ get; set; }
public double L{
get{
return Math.Sqrt(X * X + Y * Y);
}
}
}
正如BenJ所指出的,您可以使用属性 而不是将x和y声明为类中的简单字段。可以通过以下方式将它们声明为属性:
private double x;
public double X
get
{
return this.x;
}
set
{
this.x = value;
this.length()
//Above line will call your desired method
}
使用计算属性可以实现类似的行为,如
double Length
{
get { return Math.sqrt(x*x+y*y); }
}
唯一需要注意的是,每次调用Length时都会执行计算,即使x和y没有改变
您可以像setter一样将x和y字段封装到属性中,并调用length函数
double X
{
get { return x; }
set
{
x = value;
length();
}
}
double Y
{
get { return y; }
set
{
y = value;
length();
}
}
然后仅通过x和y属性更改x和y
你认为这个机制如何运作?这不是魔术…必须检查x和y的值,一旦它们改变,调用你的方法…可能是重复的谢谢,本。现在我有另一个问题。我把x和y包裹在一节课上。因此,x和y在不进行设置的情况下更新。因为我从来没有设置变量,所以永远不会调用length