【问题标题】:How to set Dictionary as a property ? Give an example如何将字典设置为属性?举个例子
【发布时间】:2016-05-12 03:56:55
【问题描述】:

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

【问题讨论】:

  • 发布您尝试过的内容。
  • 您可能必须在字典属性上使用字典函数(添加/删除),如下所示:MyObjInstance.dictionaryProperty.Add("key", value);
  • 字典作为属性应该期望一个字典对象被设置并通过get返回。在属性“set”中设置一个值似乎不正确,因为它是一种集合。更好的是,您可以将字典作为一个字段并公开几个方法“添加”、“删除”并使用字典进行操作。
  • 我已经解决了我自己。感谢您的支持。

标签: c# .net properties getter-setter


【解决方案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";

【讨论】:

    【解决方案2】:
    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>();
         }
     }
    

    【讨论】:

      【解决方案3】:

      你是这个意思吗?

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        相关资源
        最近更新 更多