1

如何将值静态分配给字典,其中值是另一个类/对象。就像下面的链接:C#:Dictionary<K,V> 如何在没有 Add(KeyValuePair<K,V>) 的情况下实现 ICollection<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; }
}
4

2 回答 2

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 }}   
};
于 2012-12-22T08:39:23.033 回答
1

使用对象初始化器来设置对象的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 }}   
};
于 2012-12-22T08:39:16.063 回答