如何将字典设置为 属性 ?举个例子

How to set Dictionary as a property ? Give an example

我正在尝试使用字典作为 class 成员。我想要 使用 属性 到 get/set 字典的 key/value 但我 困惑于如何将字典用作 属性。因为有2 零件,我不知道如何设置 get/sets。

你可以试试这个:

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";
using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
    Console.WriteLine("Hello World");
    var cl = new cl();
    populate(cl.dict);

    foreach(var d in cl.dict)
        Console.WriteLine(d.Key);
}

private static void populate(Dictionary<int, string> d)
{
    for (int i = 0; i < 10 ;  i++)
    {
        if (!d.ContainsKey(i))
        {
            d.Add(i, i.ToString());
        }
    }
    }
}

public class cl
{
    public Dictionary<int, string> dict;
    public cl()
     {
       dict = new Dictionary<int, string>();
     }
 }

你是这个意思吗?

class MyDictionary<TKey, TValue>
{
    private readonly Dictionary<TKey, TValue> _dictionary;

    public void Add(TKey key, TValue value)
    {
        _dictionary.Add(key, value);
    }

    public void Clear()
    {
        _dictionary.Clear();
    }

    public bool Remve(TKey key)
    {
        return _dictionary.Remove(key);
    }

...和其他方法...

    public MyDictionary(Dictionary<TKey, TValue> dictionary)
    {
        _dictionary = dictionary;
    }
}