[java] C #에서 동등한 Java Map

선택 키를 사용하여 컬렉션의 항목 목록을 보유하려고합니다. Java에서는 간단히 다음과 같이 Map을 사용합니다.

class Test {
  Map<Integer,String> entities;

  public String getEntity(Integer code) {
    return this.entities.get(code);
  }
}

C # 에서이 작업을 수행하는 동등한 방법이 있습니까?
System.Collections.Generic.Hashset해시를 사용하지 않으며 사용자 정의 유형 키를 정의 할 수 없습니다
System.Collections.Hashtable일반 클래스
System.Collections.Generic.Dictionary에는 get(Key)메소드 가 없습니다



답변

사전을 인덱싱 할 수 있으며 ‘get’이 필요하지 않았습니다.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

값을 테스트 / 가져 오는 효율적인 방법은 TryGetValue(Earwicker에게 감사)입니다.

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

이 방법을 사용하면 값을 빠르고 예외없이 얻을 수 있습니다 (있는 경우).

자원:

사전 키

가치를 얻으십시오


답변

Dictionary <,>는 동등합니다. Get (…) 메서드는 없지만 인덱스 표기법을 사용하여 C #에서 직접 액세스 할 수있는 Item이라는 인덱스 속성이 있습니다.

class Test {
  Dictionary<int,String> entities;

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

사용자 정의 키 유형을 사용하려면 기본 (참조 또는 구조체) 동등이 키의 동등성을 결정하기에 충분하지 않으면 IEquatable <> 구현 및 Equals (object) 및 GetHashCode ()를 재정의하는 것이 좋습니다. 키가 사전에 삽입 된 후 키가 변형 된 경우 (예 : 돌연변이로 인해 해시 코드가 변경 되었기 때문에) 이상한 일이 발생하지 않도록 키 유형을 변경할 수 없도록해야합니다.


답변

class Test
{
    Dictionary<int, string> entities;

    public string GetEntity(int code)
    {
        // java's get method returns null when the key has no mapping
        // so we'll do the same

        string val;
        if (entities.TryGetValue(code, out val))
            return val;
        else
            return null;
    }
}


답변