.NET Dictionary as a Property

眉间皱痕 提交于 2019-12-31 11:29:27

问题


Can someone point me out to some C# code examples or provide some code, where a Dictionary has been used as a property for a Class.

The examples I have seen so far don't cover all the aspects viz how to declare the dictionary as property, add, remove, and retrieve the elements from the dictionary.


回答1:


Here's a quick example

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

Some use cases

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



回答2:


sample code:

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; }
}

sample usage:

MyClass mc = new MyClass();

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

Console.WriteLine(mc.TheDictionary[2]);

EDIT

When you use C# version 6 or later, you can also use this:

public class MyClass
{
  // you don't need a constructor for this feature

  // no (public) setter so no-one can change the dictionary itself
  // it is set when creating a new instance of MyClass
  public IDictionary<int, string> TheDictionary { get; } = new Dictionary<int, string>();
}



回答3:


You could also look into indexers. (official MSDN documentation 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];
        }
    }
}

Then, once you have populated the dictionary internally, you can access it's information by going

MyClass myExample = new MyClass();

string turingBio = myExample["Turing, Alan"];

EDIT

Obviously, this has to be used carefully, because MyClass is NOT a dictionary, and you cannot use any dictionary methods on it unless you implement them for the wrapper class. But indexers are a great tool in certain situations.




回答4:


In order to ensure the encapsulation is correct and the dictionary cannot be updated outside the class using Add or the form ExampleDictionary[1]= "test", use 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; }
    }
}

The following code will not work, which is not the case if IDictionary is used:

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



回答5:


Another example of using a dictionary as a static property with only the get accessor:

  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}
    }          

This structure can be used to replace values.




回答6:


An example...

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);
    }
}



回答7:


Since .net 4.6 you can also define a Dictionary like this:

private Dictionary<string,int> Values => new Dictionary<string, int>()
{
    { "Value_1", 1},
    { "Value_2", 2},
    { "Value_3", 3},
};

It's called Expression-bodied members!




回答8:


You mean like a property bag ?

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



来源:https://stackoverflow.com/questions/980991/net-dictionary-as-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!