.NET字典作为属性

Ana*_*hah 26 .net c# dictionary properties

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

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

Jar*_*Par 38

这是一个简单的例子

class Example {
  private Dictionary<int,string> _map;
  public Dictionary<int,string> Map { get { return _map; } }
  public Example() { _map = new Dictionary<int,string>(); }
}
Run Code Online (Sandbox Code Playgroud)

一些用例

var e = new Example();
e.Map[42] = "The Answer";
Run Code Online (Sandbox Code Playgroud)

  • 是的,正确的“ 42”是“生命,宇宙和一切终极问题的答案”。 (2认同)

Han*_*ing 17

示例代码:

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; }
}
Run Code Online (Sandbox Code Playgroud)

样品用量:

MyClass mc = new MyClass();

mc.TheDictionary.Add(1, "one");
mc.TheDictionary.Add(2, "two");
mc.TheDictionary.Add(3, "three");

Console.WriteLine(mc.TheDictionary[2]);
Run Code Online (Sandbox Code Playgroud)

  • 我会考虑将属性公开为IDictionary <int,string>而不是整个类. (4认同)

Dev*_*inB 12

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

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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,一旦您在内部填充了字典,就可以通过访问它来访问它的信息

MyClass myExample = new MyClass();

string turingBio = myExample["Turing, Alan"];
Run Code Online (Sandbox Code Playgroud)

编辑

显然,这必须谨慎使用,因为MyClass它不是字典,除非你为包装类实现它们,否则你不能在它上面使用任何字典方法.但在某些情况下,索引器是一个很好的工具.