IT박스

주어진 키가 사전에 없습니다.

itboxs 2020. 11. 12. 08:03
반응형

주어진 키가 사전에 없습니다. 어떤 열쇠?


모든 제네릭 클래스에 영향을 미치는 방식으로 C #의 다음 예외에서 주어진 키의 값을 가져 오는 방법이 있습니까? Microsoft의 예외 설명에서 이것이 큰 실수라고 생각합니다.

"The given key was not present in the dictionary."

더 좋은 방법은 다음과 같습니다.

"The given key '" + key.ToString() + "' was not present in the dictionary."

솔루션에는 믹스 인 또는 파생 클래스가 포함될 수 있습니다.


이 예외는 존재하지 않는 항목을 색인화하려고 할 때 발생합니다. 예를 들면 다음과 같습니다.

Dictionary<String, String> test = new Dictionary<String,String>();
test.Add("Key1,"Value1");
string error = test["Key2"];

종종 물건과 같은 것이 열쇠가 될 것이며, 이는 의심 할 여지없이 얻기 어렵게 만듭니다. 그러나 항상 다음을 작성할 수 있습니다 (또는 확장 메서드로 래핑 할 수도 있음).

if (test.ContainsKey(myKey))
   return test[myKey];
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

또는 더 효율적입니다 (@ScottChamberlain 덕분에)

T retValue;
if (test.TryGetValue(myKey, out retValue))
    return retValue;
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Microsoft는 이것을하지 않기로 결정했습니다. 아마도 대부분의 개체에서 사용할 때 쓸모가 없기 때문일 것입니다. 스스로 할 수있을만큼 간단하므로 직접 굴려보세요!


일반적인 경우 대답은 아니오입니다.

그러나 예외가 처음 발생한 지점에서 중단되도록 디버거를 설정할 수 있습니다. 이때 존재하지 않는 키는 호출 스택의 값으로 액세스 할 수 있습니다.

Visual Studio에서이 옵션은 다음 위치에 있습니다.

디버그 → 예외 ... → 공용 언어 런타임 예외 → System.Collections.Generic

거기에서 던진 상자를 확인할 수 있습니다 .


런타임에 정보가 필요한보다 구체적인 인스턴스의 경우 코드에서를 사용 IDictionary<TKey, TValue>하고에 직접 연결되지 않은 Dictionary<TKey, TValue>경우이 동작을 제공하는 자체 사전 클래스를 구현할 수 있습니다.


키 누락을 관리하려면 TryGetValue를 사용해야합니다.

https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx

string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

이 코드를 시도해 볼 수 있습니다.

Dictionary<string,string> AllFields = new Dictionary<string,string>();  
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);

키가 없으면 단순히 null 값을 반환합니다.


string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"

With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.

참고URL : https://stackoverflow.com/questions/26244336/the-given-key-was-not-present-in-the-dictionary-which-key

반응형