如果我有一个私有变量,我想对其进行一些内部验证,并希望将该验证保存在一个地方,我会将其放在getter/setter后面,并仅通过该getter/setter访问它。这在处理公共属性时很有用,因为其他代码不能访问私有变量,但是当我处理类本身内部的对象时,有没有办法强制使用getter/setter?
private int _eyeOrientation;
private int eyeOrientation
{
get
{
return _eyeOrientation;
}
set
{
if (value < 0)
{
_eyeOrientation = 0;
}
else
{
_eyeOrientation = value % 360;
}
}
}
这里的问题是,类中的其他函数可能会意外地修改
_eyeOrientation = -1;
这会使程序陷入混乱。有没有办法让它抛出一个编译器错误?
发布于 2009-05-11 16:30:58
听起来你需要一个角度类型。
// Non mutable Angle class with a normalized, integer angle-value
public struct Angle
{
public Angle(int value)
{
Value = value;
}
private angle;
public Value
{
get { return angle; }
private set { angle = Normalize(value); }
}
public static int Normalize(int value)
{
if (value < 0) return 360 - (value % 360);
return value % 360;
}
}
public class SomeClass
{
public Angle EyeOrientation { get; set; }
}
如果你有一个特定类型的值,比如角度、金钱、权重等等,最好把它变成自己的类型,即使这个值本身存储在int、decimal等类型中,这种类型也会让你的接口更清晰、类型更安全。如果你期望一个角度或整数值作为某些方法的参数,这是不一样的。
发布于 2009-05-11 16:14:15
一般来说,您不应该担心这一点。如果您不想将检查放在类本身中,类成员仍然可以使用这些属性。
如果您的类变得太大,以至于您不再信任类中的方法,我认为是时候开始重构并将其分解为更易于管理的更小的类了。
发布于 2009-05-11 16:11:09
你可以在一个嵌套的类中定义它。
public class NeedsEye
{
Eye _eye = new Eye();
public NeedsEye()
{
// now, here, any access to the property must be made through the
// _eye variable. The Eye class has access to any of the properties
// and members of the NeedsEye class, but the NeedsEye class has not
// any access to members of the Eye class.
}
private class Eye
{
private int _orientation;
public int Orientation
{
get { return _orientation; }
if (value < 0)
{
_eyeOrientation = 0;
}
else
{
_eyeOrientation = value % 360;
}
}
}
}
https://stackoverflow.com/questions/850586
复制相似问题