1

値が別のクラス/オブジェクトである Dictionary に値を静的に割り当てるにはどうすればよいですか。次のリンクのように: 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; }
}
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 に答える