Java Map equivalent in C#

前端 未结 3 1553
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 12:29

I\'m trying to hold a list of items in a collection with a key of my choice. In Java, I would simply use Map as follows:

class Test {
  Map         


        
3条回答
  •  死守一世寂寞
    2021-01-30 12:31

    Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

    class Test {
      Dictionary entities;
    
      public String getEntity(int code) {
        return this.entities[code];
      }
    }
    

    If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

提交回复
热议问题