imp*_*mja 6 c# class-design properties
前几天我碰到了一些关于C#属性的问题.
假设我有这个设置:
public class Point
{
public float X;
public float Y;
}
public class Control
{
protected Point m_Position = new Point();
public Point Position
{
get { return m_Position; }
set
{
m_Position = value; }
// reorganize internal structure..
reorganize();
}
protected reorganize()
{
// do some stuff
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但在使用方面,我可以这样写:
Control myControl = new Control();
myControl.Position.X = 1.0f;
Run Code Online (Sandbox Code Playgroud)
问题是,我的Control班级不会认识到Position因为set()没有被调用而已经改变了.
有没有办法让人Control知道任何Position变化?
在这种情况下有很多选择:
在这种情况下,我会建议选项#1
One*_*HOT -3
这应该可以解决它!我在 getter 中添加了一行,用于测试该点是否为空以及是否在返回之前实例化它。
public class Point
{
public float X;
public float Y;
}
public class Control
{
protected Point m_Position = new Point();
public Point Position
{
get
{
if (m_Position == null) m_Position = new Point();
return m_Position;
}
set
{
m_Position = value;
// reorganize internal structure..
reorganize();
}
}
protected reorganize()
{
// do some stuff
}
}
Run Code Online (Sandbox Code Playgroud)
华泰