有没有办法强制我的其他类来访问属性设置器而不是支持字段?请考虑以下笨拙的代码:
public class Brittle
{
private string _somethingWorthProtecting;
public string SomethingWorthProtecting
{
get { return _somethingWorthProtecting; }
set
{
_somethingWorthProtecting = value;
ReallyNeedToDoThisEverTimeTheValueChanges();
}
}
public void OhDearWhatWasIThinking()
{
_somethingWorthProtecting = "Shooting myself in the foot here, aren't I?";
}
}
据我所知,C#没有提供任何机制来阻止类开发人员犯这个错误。 (在这种情况下,自动属性显然不是一种选择。)是否有一种设计模式或实践可以帮助防止这种无意的终端?
答案 0 :(得分:1)
您可以将该逻辑移动到抽象基类:
public abstract class Brittle
{
private string _somethingWorthProtecting;
public string SomethingWorthProtecting
{
get { return _somethingWorthProtecting; }
set
{
_somethingWorthProtecting = value;
ReallyNeedToDoThisEverTimeTheValueChanges();
}
}
//.....
}
然后你可以确定没有人会实例化这个类,派生类将无法访问私有字段。
public class BrittleDerived : Brittle
{
public void DoSomething()
{
// cannot access _somethingWorthProtecting;
}
}