我有一个 Properties
类,我在其中定义了一个像这样的字典:
public class Properties
{
public IDictionary<string, string> ExtendedProperties
{
get;
set;
}
}
在字典中,将始终存在 3 个键,例如 Name
、Number
和 Age
,可以选择添加更多 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; }
}
如果你添加这样的东西,你可以做 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/