有人可以指出我对某些C#代码示例或提供一些代码,其中一个字典已被用作一个类的属性。作为一个属性的.NET词典
到目前为止,我看到的例子并没有涵盖所有方面,即如何将字典声明为属性,添加,删除和检索字典中的元素。
有人可以指出我对某些C#代码示例或提供一些代码,其中一个字典已被用作一个类的属性。作为一个属性的.NET词典
到目前为止,我看到的例子并没有涵盖所有方面,即如何将字典声明为属性,添加,删除和检索字典中的元素。
这里有一个简单的例子
class Example {
private Dictionary<int,string> _map;
public Dictionary<int,string> Map { get { return _map; } }
public Example() { _map = new Dictionary<int,string>(); }
}
一些使用情况
var e = new Example();
e.Map[42] = "The Answer";
示例代码:
public class MyClass
{
public MyClass()
{
TheDictionary = new Dictionary<int, string>();
}
// private setter so no-one can change the dictionary itself
// so create it in the constructor
public IDictionary<int, string> TheDictionary { get; private set; }
}
示例用法:
MyClass mc = new MyClass();
mc.TheDictionary.Add(1, "one");
mc.TheDictionary.Add(2, "two");
mc.TheDictionary.Add(3, "three");
Console.WriteLine(mc.TheDictionary[2]);
我会考虑露出财产的IDictionary
好的,更改了属性 – 2010-03-19 08:51:11
一个例子...
public class Example
{
public Dictionary<Int32, String> DictionaryProperty
{
get; set;
}
public Example()
{
DictionaryProperty = new Dictionary<int, string>();
}
}
public class MainForm
{
public MainForm()
{
Example e = new Example();
e.DictionaryProperty.Add(1, "Hello");
e.DictionaryProperty.Remove(1);
}
}
你也可以考虑indexers。 (官方的MSDN文档here)
class MyClass
{
private Dictionary<string, string> data = new Dictionary<string, string>();
public MyClass()
{
data.Add("Turing, Alan", "Alan Mathison Turing, OBE, FRS (pronounced /ˈtjʊ(ə)rɪŋ/) (23 June, 1912 – 7 June, 1954) was a British mathematician, logician, cryptanalyst and computer scientist.")
//Courtesy of [Wikipedia][3]. Used without permission
}
public string this [string index]
{
get
{
return data[index];
}
}
}
然后,一旦你已经填充内部字典,你可以访问它的信息通过去
MyClass myExample = new MyClass();
string turingBio = myExample["Turing, Alan"];
编辑
显然,这是请谨慎使用,因为MyClass
不是字典,除非您为包装类实现它们,否则不能在其上使用任何字典方法。但是索引器在某些情况下是一个很好的工具。
使用字典作为静态属性只有get访问的另一实例:
private static Dictionary <string, string> dict = new Dictionary <string,string>(){
{"Design Matrix", "Design Case"},
{"N/A", "Other"}
};
public static Dictionary <string, string> Dict
{
get { return dict}
}
这种结构可以用来替换值。
为了确保封装是正确的,并且使用Add或ExampleDictionary [1] =“test”形式的字典无法在类外更新,请使用IReadOnlyDictionary。
public class Example
{
private Dictionary<int, string> exampleDictionary;
public Example()
{
exampleDictionary = new Dictionary<int, string>();
}
public IReadOnlyDictionary<int, string> ExampleDictionary
{
get { return (IReadOnlyDictionary<int, string>)exampleDictionary; }
}
}
下面的代码将无法正常工作,如果使用的IDictionary这是不是这样的:
var example = new Example();
example.ExampleDictionary[1] = test;
是的,正确的“42”是“回答生命,宇宙和万物的终极问题”。 – Equiman 2017-12-26 13:03:52