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

时间:2016-02-03 04:59:39

标签: c# .net properties getter-setter

我试图将字典用作类成员。我想要 使用属性来获取/设置字典的键/值,但我是 混淆为如何使用字典作为属性。既然有2个 部分,我不知道如何设置get / sets。

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你是说这个吗?

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