2012-12-22 25 views
1

如何靜態地將值分配給字典,其中的值是另一個類/對象。就像在以下鏈接:C#: How can Dictionary<K,V> implement ICollection<KeyValuePair<K,V>> without having Add(KeyValuePair<K,V>)?如何靜態分配詞典<TKey,TValue>值

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

回答

5

的值必須初始化的對象:

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

使用一個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 }} 
};