.NET字典作为属性

有人可以指出我的一些C#代码示例或提供一些代码,其中Dictionary已被用作Class的属性。

到目前为止我看到的示例并未涵盖所有方面,即如何将字典声明为属性,添加,删除和检索字典中的元素。

这是一个简单的例子

class Example { private Dictionary _map; public Dictionary Map { get { return _map; } } public Example() { _map = new Dictionary(); } } 

一些用例

 var e = new Example(); e.Map[42] = "The Answer"; 

示例代码:

 public class MyClass { public MyClass() { TheDictionary = new Dictionary(); } // private setter so no-one can change the dictionary itself // so create it in the constructor public IDictionary 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]); 

您还可以查看索引器 。 (官方MSDN文档在这里 )

 class MyClass { private Dictionary data = new Dictionary(); 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不是字典,除非为包装类实现它们,否则不能在其上使用任何字典方法。 但在某些情况下,索引器是一个很好的工具。

为了确保封装正确并且无法使用Add或表单ExampleDictionary [1] =“test”在类外部更新字典,请使用IReadOnlyDictionary。

 public class Example { private Dictionary exampleDictionary; public Example() { exampleDictionary = new Dictionary(); } public IReadOnlyDictionary ExampleDictionary { get { return (IReadOnlyDictionary)exampleDictionary; } } } 

以下代码不起作用,如果使用IDictionary则不然:

 var example = new Example(); example.ExampleDictionary[1] = test; 

将字典用作仅具有get访问器的静态属性的另一个示例:

  private static Dictionary  dict = new Dictionary (){ {"Design Matrix", "Design Case"}, {"N/A", "Other"} }; public static Dictionary  Dict { get { return dict} } 

此结构可用于替换值。

一个例子…

 public class Example { public Dictionary DictionaryProperty { get; set; } public Example() { DictionaryProperty = new Dictionary(); } } public class MainForm { public MainForm() { Example e = new Example(); e.DictionaryProperty.Add(1, "Hello"); e.DictionaryProperty.Remove(1); } } 

你的意思是像一个财产袋?

http://www.codeproject.com/KB/recipes/propertybag.aspx