如何强制 child 类 实现包含特定值的集合 属性

How to enforce child classes to implement a collection property containing a specific value

我有一个抽象基础 class 和一个抽象字典 属性:

public abstract class BaseClass
{
    //...
    public abstract Dictionary<string, object> Settings { get; set; }
    //...
}

我希望 child classes 使用名为 "Text" 的特定密钥来实现此 属性(如果需要,可以添加更多密钥,但 "Text" 键必须存在),例如:

public class ChildClass : BaseClass
{
    //...
    private Dictionary<string, object> _settings = new Dictionary<string, object>()
    {
        { "Text", "SomeText" }
    };
    public Dictionary<string, object> Settings
    {
        get{ return _settings; }
        set{ _settings = value; }
    }
    //...   
}

强制执行 child classes 的最佳方法是什么,不仅要实现 属性,还要确保它包含一个名为 "Text" 的键和一个关联值?

我只想让设置 属性 非抽象。

public abstract class BaseClass
{
    //...
    protected Dictionary<string, object> Settings { get; set; }
    public BaseClass()
    {
        Settings = new Dictionary<string, object>()
        {
            { "Text", "SomeText" }
        };
    }
    //...
}

正如其他人所建议的那样,我将隐藏设置(字典)的实现,并公开访问数据的方法:

public abstract class BaseClass
{
    //...
    private readonly Dictionary<string, object> _settings = new Dictionary<string, object>();

    protected BaseClass() { }

    public object GetSetting(string name)
    {
        if ("Text".Equals(name))
        {
            return this.GetTextValue();
        }
        return this._settings[name];
    }

    // this forces every derived class to have a "Text" value
    // the value could be hard coded in derived classes of held as a variable
    protected abstract GetTextValue();

    protected void AddSetting(string name, object value)
    {
        this._settings[name] = value;
    }


    //...
}

感谢您的回答。看起来没有一个很好的方法来强制子 属性 包含特定的键而不将字典封装在基础 class 中并编写自定义获取、设置方法或编写另一个 class保留设置。

事实证明,在我的情况下,我只需要对设置 属性 进行只读访问,所以我最终更改为基于 class 的受保护字典 属性一个 public 只读字典包装器来公开内容。然后我通过构造函数参数在 "Text" 键上强制设置。毕竟不需要抽象属性。