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

本文关键字:属性 字典 设置 | 更新日期: 2023-09-27 18:32:55

我正在尝试使用字典作为类成员。我想使用属性获取/设置字典的键/值,但我是困惑于如何将字典用作属性。由于有 2部分,我不知道如何设置获取/设置。

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

你可以试试这个:

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