2016-09-15 84 views
1

我有一个抽象基类的抽象字典属性,集合属性:如何执行子类来实现包含特定值

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

我想子类实现与所谓的特定键此属性“文本”(多个键如果需要,可以添加,但‘文字’键必须存在),例如:

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; } 
    } 
    //... 
} 

什么是强制执行的子类,不仅实现了财产,但以确保它包含的最佳方式一个名为“文本”的关键值的关键?

+1

唯一的方法是将字典的操作封装在基类中。它实际上尖叫着创建一个Settings类而不是使用Dictionary。如果您只是公开字典,则无法控制添加/删除键。 – itsme86

+0

不要暴露'Dictionary'(使其对基类不公开),但例如'IReadonlyDictionary'并提供操作字典的方法(添加,删除,与其他等结合)。这样你就可以完全控制它的内容。 – Sinatr

回答

2

正如其他人建议我将隐藏的设置(字典)的执行情况,并揭露方法来访问数据:

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; 
    } 


    //... 
} 
+0

我最终重组了我的结构,所以这不适用,但我接受它作为原始问题的最佳答案 –

0

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

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

感谢您的答案。看起来好像没有一种好方法来强制子属性包含特定的键,而无需在基类中封装字典并编写自定义get,设置方法或编写另一个类来保存设置。

事实证明,在我的情况下,我只需要只读访问Settings属性,因此我最终使用公共只读字典包装器更改为基类的受保护字典属性以公开内容。然后,我通过构造函数参数强制执行“文本”键上的设置。毕竟不需要抽象属性。

相关问题