如何对 class 的其余部分隐藏支持字段

How to hide the backing field from the rest of the class

有什么方法可以强制我的 class 的其余部分访问 属性 setter 而不是支持字段?考虑以下笨拙的代码:

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# 没有提供任何机制来防止 class 开发人员犯这种错误。 (在这种情况下,自动属性显然不是一个选项。)是否有设计模式或实践可以帮助防止这种无意的结束?

您可以将该逻辑移至抽象基础 class:

public abstract class Brittle
{
    private string _somethingWorthProtecting;
    public string SomethingWorthProtecting 
    {
        get { return _somethingWorthProtecting; }
        set
        {
            _somethingWorthProtecting = value;
            ReallyNeedToDoThisEverTimeTheValueChanges();
        }
    }

    //.....
}

那么你可以确定没有人会实例化这个 class,并且派生的 classes 将无法访问私有字段。

public class BrittleDerived : Brittle
{
     public void DoSomething() 
     {
        // cannot access _somethingWorthProtecting;
     }
}