【问题标题】:How to statically assign Dictionary<TKey, TValue> values如何静态分配 Dictionary<TKey, TValue> 值
【发布时间】:2012-12-22 08:36:42
【问题描述】:

如何将值静态分配给字典,其中值是另一个类/对象。喜欢下面的链接:C#: How can Dictionary<K,V> implement ICollection<KeyValuePair<K,V>> without having Add(KeyValuePair<K,V>)?

class Settings
{
    public Dictionary<SettingKey, SettingItem> List =
        new Dictionary<SettingKey, SettingItem>()
    {
        {SettingKey.userDBName,{ theValue = "user-name", theID = 1 }},
        {SettingKey.realName,{ theValue = "real-name", theID = 2 }}   
    };
}

enum SettingKey
{
    userDBName,
    realName 
}

class SettingItem
{
    public string theValue { get; set; }
    public int theID { get; set; }
}

【问题讨论】:

    标签: c# collections


    【解决方案1】:

    您必须初始化对象:

    public Dictionary<SettingKey, SettingItem> List =
        new Dictionary<SettingKey, SettingItem>()
    {
        {SettingKey.userDBName, new SettingItem { theValue = "user-name", theID  = 1 }},
        {SettingKey.realName,   new SettingItem { theValue = "real-name", theID  = 2 }}   
    };
    

    【讨论】:

      【解决方案2】:

      使用object initializer 设置SettingItem 对象的值

      public Dictionary<SettingKey, SettingItem> List =
          new Dictionary<SettingKey, SettingItem>()
      {
          {SettingKey.userDBName, new SettingItem { theValue = "user-name", theID = 1 }},
          {SettingKey.realName, new SettingItem { theValue = "real-name", theID = 2 }}   
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-14
        • 2011-04-11
        • 1970-01-01
        • 2011-01-16
        • 1970-01-01
        • 2010-10-08
        相关资源
        最近更新 更多