c# - 使用预填充键定义字典 ​​c#

标签 c# dictionary

我有一个 Properties 类,我在其中定义了一个像这样的字典:

 public class Properties
    {
        public IDictionary<string, string> ExtendedProperties
        {
            get;
            set;
        }
    }

在字典中,将始终存在 3 个键,例如 NameNumberAge,可以选择添加更多 KeyValuePairs 在运行时。

我希望在我的代码中初始化字典时默认将上面描述的 3 个键存在,以便我可以像这样直接使用它:

Properties objProps = new Properties();
objProps.ExtendedProperties["Name"] = "SomeName";

我知道我可以通过将 KeyValuePair 添加到字典中来在我的代码中实现这一点,但我希望使用 get-set 直接在类中设置它以包含 3 个键。我在类里面找不到任何解决方案。我调查了这个Creating dictionaries with predefined keys但并不满意。

我怎样才能做到这一点?

最佳答案

从 C# 6 开始,您可以执行以下操作:

using System;
using System.Collections.Generic;

public class Properties
{
    public IDictionary<string, string> ExtendedProperties { get; set; }

    public Properties(string name, string number, string age) 
    {
        this.ExtendedProperties = new Dictionary<string, string>() 
        { 
            ["Name"] = name,
            ["Number"] = number,
            ["Age"] = age
        };
    }
}

如您所见,您需要在构造函数中定义它。

您可能还想使用一些很酷的功能:

public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

Documentation

如果你添加这样的东西,你可以做 new Properties()["Name"]

您的代码示例:

using System;
using System.Collections.Generic;

public class Properties
{
    private IDictionary<string, string> extendedProperties;

    public string this[string key] 
    {
        get { return extendedProperties[key]; }
        set { extendedProperties[key] = value; }        
    }

    public Properties() 
    {
        this.extendedProperties = new Dictionary<string, string>() 
        { 
            ["Name"] = "something",
            ["Number"] = "something",
            ["Age"] = "something"
        };
    }
}

关于c# - 使用预填充键定义字典 ​​c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32712487/

相关文章:

c++ - 在 std set/map 中使用 double 作为键的方法

python - 使用对象内存位置作为哈希键

c++ - 尝试访问结构中的 map 时程序卡住

c# - System.Console.Write ("{0}{1:N2} {2}"什么是 {1 :N2} referring to?

c# - 具有非接口(interface)的构造函数参数的依赖注入(inject)

C# Windows 窗体单元测试

python - 根据字典用数值替换字符串

c# - 如何在运行时更改 Web API 的连接字符串

c# - 清除 Sitecore 的 .NET 缓存

swift - 如何在 Swift 中将核心数据对象提取到字典中?