【问题标题】:How can I combine a method and a dictionary used by the method for lookups? [duplicate]如何将方法和该方法使用的字典组合起来进行查找? [复制]
【发布时间】:2012-09-07 20:39:40
【问题描述】:

可能重复:
Creating a constant Dictionary in C#

我目前有:

    public string GetRefStat(int pk) {
        return RefStat[pk];
    }
    private readonly Dictionary<int, int> RefStat =
    new Dictionary<int, int> 
    {
        {1,2},
        {2,3},
        {3,5} 
    };

这可行,但我唯一一次使用 RefStat 字典是在 GetRefStat 调用它时。

有没有办法可以将方法和字典结合起来?

【问题讨论】:

  • 这两个还没有合并到一个类中吗?

标签: c#


【解决方案1】:

是的,您可以在类型的构造函数中初始化字典。然后,您可以将方法 GetRefStat 更改为属性。所以元代码可能是这样的

class Foo
{
    public Dictionary<int, int> RefStat {get;private set;}

    Foo()
    {
        RefStat = new Dictionary<int, int> 
        {
            {1,2},
            {2,3},
            {3,5} 
        };
    }
}

及用法

Foo f = new Foo();
var item = f.RefStat[0] 

【讨论】:

    【解决方案2】:

    你可以做一个扩展方法,然后所有的字典都可以使用这个函数。我将假设GetRefStat 不仅仅是简单地使用键从字典中获取值:

    public static class DictionaryExtensions
    {
        public static TValue GetRefStat<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key) 
        {
            return dictionary[key];
        }
    }
    

    那么所有的字典都可以这样称呼它:

    var dictionary = new Dictionary<int, int> 
        {
            {1,2},
            {2,3},
            {3,5} 
        };
    var value = dictionary.GetRefStat(2)
    

    如果这本字典是一堆常量,那么这个答案就过分了。只需使用if/elseswitch

    【讨论】:

      【解决方案3】:

      这样的?

       public string GetRefStat(int pk) 
      { 
          return new Dictionary<int, int>   
          {  
              {1,2},  
              {2,3},  
              {3,5}   
          }[pk]; 
      } 
      

      【讨论】:

      • 为每次查找创建一个新的字典对象是一个糟糕的主意。
      • 对于类型实例,此类函数通常会被调用一次。所以它可能没有你想象的那么可怕。
      • 典型? OP 想要一组数字之间的编译时定义的映射。您在对象实例化、散列、创建存储桶和垃圾收集方面浪费了周期。
      猜你喜欢
      • 2015-12-31
      • 2011-06-06
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 2019-05-07
      相关资源
      最近更新 更多