【问题标题】:.NET Dictionary as a Property.NET 字典作为属性
【发布时间】:2010-11-02 03:11:02
【问题描述】:

谁能指出一些 C# 代码示例或提供一些代码,其中字典已用作类的属性。

到目前为止,我所看到的示例并未涵盖所有方面,即如何将字典声明为属性、添加、删除和检索字典中的元素。

【问题讨论】:

    标签: c# .net dictionary properties


    【解决方案1】:

    你的意思是像一个财产袋?

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

    【讨论】:

      【解决方案2】:

      示例代码:

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

      示例用法:

      MyClass mc = new MyClass();
      
      mc.TheDictionary.Add(1, "one");
      mc.TheDictionary.Add(2, "two");
      mc.TheDictionary.Add(3, "three");
      
      Console.WriteLine(mc.TheDictionary[2]);
      

      编辑

      当你使用 C# 版本 6 或更高版本时,你也可以使用这个:

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

      【讨论】:

      • 我会考虑将属性公开为 IDictionary 而不是整个类。
      【解决方案3】:

      这是一个简单的例子

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

      【讨论】:

      • 是的,“42”是“生命、宇宙和一切终极问题的答案”。
      【解决方案4】:

      一个例子...

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

      【讨论】:

        【解决方案5】:

        您也可以查看indexers。 (MSDN 官方文档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];
                }
            }
        }
        

        然后,一旦你在内部填充了字典,你就可以通过去访问它的信息

        MyClass myExample = new MyClass();
        
        string turingBio = myExample["Turing, Alan"];
        

        编辑

        显然,这必须小心使用,因为MyClass 不是字典,并且您不能在其上使用任何字典方法,除非您为包装类实现它们。但索引器在某些情况下是一个很好的工具。

        【讨论】:

          【解决方案6】:

          另一个使用字典作为静态属性的例子,只有 get 访问器:

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

          这个结构可以用来替换值。

          【讨论】:

            【解决方案7】:

            为了确保封装正确且字典不能在类外使用 Add 或 ExampleDictionary[1]="test" 形式更新,请使用 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; }
                }
            }
            

            下面的代码将不起作用,如果使用 IDictionary 则不是这样:

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

            【讨论】:

            • 我知道 OP(有点)明确表示他希望该属性具有 IDictionary 的功能,但我不知道 IReadOnlyDictionary 并且需要它。 +1
            • 如果你真的想防止修改字典的内容,一个简单的转换到IReadOnlyDictionary 是不够的,一个简单的转换回字典将允许修改它。您应该将 Dictionary 包装到 ReadOnlyDictionary 中,并返回包装器。
            【解决方案8】:

            从 .net 4.6 开始,您还可以像这样定义字典:

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

            它叫Expression-bodied members!

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-02-09
              • 1970-01-01
              • 2011-07-30
              • 1970-01-01
              • 2017-04-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多