c# - 如何静态分配 Dictionary<TKey, TValue> 值

标签 c# collections

如何将值静态分配给字典,其中值是另一个类/对象。喜欢以下链接: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; }
}

最佳答案

您必须初始化对象:

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

关于c# - 如何静态分配 Dictionary<TKey, TValue> 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14001327/

相关文章:

c# - Marshal.PtrToStructure 在 64 位上崩溃

Java 8 : Fetching selective request parameters

java - 使用 ArrayList 检索属性?

java - 插入优先队列

c# - BlockingQueue 以何种方式阻塞?

java - Collections.shuffle 是否保证结果不排序?

C#:如何减去两个日期?

c# - C#有解析多层级联JSON的库吗?

c# - 如何在 C# 中计算 "median of five"?

c# - Linq group by 跨不同表的多个字段