【问题标题】:"More functional" "accessor" for collections in C#C# 中集合的“更多功能”“访问器”
【发布时间】:2015-04-28 12:56:44
【问题描述】:

现在我有一个收藏:Dictionary<string, List<string>> dictionary

出于某种原因,现在我想将其中的一部分“投影/映射”到其他集合,有点像将其用作支持字段,并为此集合创建不同的访问器。

like List<string> keys 对应这个字典的键,或者Dictionary<string, string> firstItems 对应一个字典,使用源字典的键作为键,源字典的值中的第一项作为值。

这可以通过在keysfirstItems 的getter/setter 中添加行为来部分完成。当我们调用keys 时,我们从dictionary 获取密钥;或者当我们调用keys = whateverTheListIs 时,dictionary 也可能会按照设计执行某些行为。

但我也想有一个“功能更强大”的“访问器”,例如,当我们调用firstItems.Add(aString, anotherString) 时,我们也在dictionary 中添加一个条目;或者当我们调用keys.Remove(yetAnotherString) 时,我们会删除dictionary 中的条目。

他们有什么办法我可以做到吗?

编辑:

这是场景(当然你可以改变它,只是为了解释):

public class Projection
{
  private Dictionary<string, List<string>> dictionary; //"backing field"

  public List<string> keys;
  public Dictionary<string, string> firstItems;
}

public static void DoSomething()
{
  Projection projection = new Projection();
  //Supposed to modify projection.dictionary too
  projection.keys = new List<string>();
  projection.keys.Add("A new Key");
}

【问题讨论】:

  • 您可以实现自己的从 IDictionary 派生的集合,然后在 .Add / .Remove 调用中添加更多功能。
  • 最好将keysfirstItems 视为只读并在要进行更改时使用原始dictionary

标签: c# collections setter getter accessor


【解决方案1】:

您可以通过继承创建自己的Dictionary

class CustomDictionary<TKey,TValue> : IDictionary<TKey, TValue>
{
    // Implement the interface IDictionary here

    public void Add(KeyValuePair<TKey, TValue> item)
    {
        // create your logic
    }
}

你可以使用合成:

class CustomDictionary<TKey,TValue>
{
    private Dictionary<TKey,TValue> _dictionary;

    public void Add(KeyValuePair<TKey, TValue> item)
    {
        // create your logic
        _dictionary.Add();
    }
}

我最喜欢的方式,你可以同时使用:

class CustomDictionary<TKey,TValue> : IDictionary<TKey,TValue>
{
    private Dictionary<TKey,TValue> _dictionary;

    // Implement the interface IDictionary here
    // send the logic to your private Dictionary

    public void Add(KeyValuePair<TKey, TValue> item)
    {
         // create your logic
        _dictionary.Add(item.Key, item.Value);
    }
}

如果您想直接从Dictionary 继承,您将面临一个问题。您不能覆盖 Add() 方法,因为它不是 virtual 方法。一个解决方案是使用关键字new 隐藏它。

class CustomDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    public new void Add(TKey key, TValue value)
    {
        // create your logic
        base.Add(key, value);
    }

    public void Add(KeyValuePair<TKey, TValue> item)
    {
        this.Add(item.Key, item.Value);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 2022-11-29
    • 2014-08-25
    相关资源
    最近更新 更多