构建静态查找

Construct a static lookup

假设我有一个巨大的定义列表,用于查找给定 "type number" 对象可以默认的值。此类型编号是唯一的,并指向对象在用它初始化时将设置为的数据。

我通常的做法是使用静态 属性,每次获取都会 return 一个新词典。例如

public static Dictionary<long, Tuple<string,DefaultValue>> Defaults
{
   get { return new Dictionary<long, DefaultValue>() 
         {
            { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
            { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
            ... 
         }
   }
}

这行得通,查找列表可能永远不会大到足以显着影响性能或内存使用,但对性能有点吝啬我不喜欢拥有新的 Dictionary每次被引用时实例化。我宁愿它完全硬编码到内存中。

如何以专业的方式解决这个问题?我觉得我上面做的方式非常草率。

您可以使用自动 属性 初始化程序或在静态构造函数中设置值。后者如下所示。

static MyClass()
{
   Defaults = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };
}

public static Dictionary<long, DefaultValue> Defaults {get; private set;}

带有 Auto-属性 初始化程序的示例(不需要静态构造函数并且省略了私有集,因为现在可以假设您使用的是支持它的 c# 版本).

public static Dictionary<long, DefaultValue> Defaults {get;} = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };

旁注:如果不应更改值,您还可以在 属性.

上公开 IReadonlyDictionary 接口

如果查找 table 很小并且您的目标是提高查找操作的性能,那么您还可以考虑使用带有 switch 语句的函数而不是查找字典。

有关详细信息,请参阅此答案: