Dictionary <>에 항목을 안전하게 추가하는 더 우아한 방법이 있습니까?
키 / 객체 쌍을 사전에 추가해야하지만, 키가 이미 존재하는지 먼저 확인해야합니다. 그렇지 않으면 " 키가 사전에 이미 있습니다 "오류가 발생합니다. 아래 코드는이 문제를 해결하지만 복잡합니다.
이와 같은 문자열 도우미 메서드를 만들지 않고이를 수행하는보다 우아한 방법은 무엇입니까?
using System;
using System.Collections.Generic;
namespace TestDictStringObject
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> currentViews = new Dictionary<string, object>();
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2");
StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1");
foreach (KeyValuePair<string, object> pair in currentViews)
{
Console.WriteLine("{0} {1}", pair.Key, pair.Value);
}
Console.ReadLine();
}
}
public static class StringHelpers
{
public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, view);
}
else
{
dict[key] = view;
}
}
}
}
인덱서를 사용하면됩니다. 이미있는 경우 덮어 쓰지만 먼저있을 필요 는 없습니다 .
Dictionary<string, object> currentViews = new Dictionary<string, object>();
currentViews["Customers"] = "view1";
currentViews["Customers"] = "view2";
currentViews["Employees"] = "view1";
currentViews["Reports"] = "view1";
기본적으로 Add
키가 존재하면 버그 (따라서 던지기를 원함)를 나타내면 인덱서가 사용됩니다. (캐스팅과 as
참조 변환에 사용하는 것의 차이점과 약간 다릅니다 .)
C # 3을 사용 하고 있고 고유 한 키 세트가있는 경우이를 더욱 깔끔하게 만들 수 있습니다.
var currentViews = new Dictionary<string, object>()
{
{ "Customers", "view2" },
{ "Employees", "view1" },
{ "Reports", "view1" },
};
컬렉션 이니셜 라이저가 항상 Add
두 번째 Customers
항목을 던질 것으로 사용하기 때문에 귀하의 경우에는 작동하지 않습니다 .
무슨 일이야 ...
dict[key] = view;
존재하지 않는 경우 자동으로 키를 추가합니다.
간단히
dict[key] = view;
Dictionary.Item의 MSDN 설명서에서
지정된 키와 연관된 값입니다. 지정된 키를 찾을 수없는 경우, get 오퍼레이션은 KeyNotFoundException을 발생시키고 set 오퍼레이션은 지정된 key로 새 요소를 작성합니다 .
나의 강조
평소와 같이 John Skeet은 정답으로 조명 속도를 제공하지만 흥미롭게도 IDIctionary에서 확장 방법으로 SafeAdd를 작성할 수도 있습니다.
public static void SafeAdd(this IDictionary<K, T>. dict, K key, T value)...
Although using the indexer is clearly the right answer for your specific problem, another more general answer to the problem of adding additional functionality to an existing type would be to define an extension method.
Obviousy this isn't a particulary useful example, but something to bear in mind for the next time you find a real need:
public static class DictionaryExtensions
{
public static void SafeAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict,
TKey key, TValue value)
{
dict[key] = value;
}
}
'Programing' 카테고리의 다른 글
"권한이있는 SSL / TLS 보안 채널에 대한 신뢰 관계를 설정할 수 없음"해결 방법 (0) | 2020.07.04 |
---|---|
Vim에 파일을 저장하기 전에 변경 사항을 볼 수 있습니까? (0) | 2020.07.04 |
HTML 형식의 이메일을 보내는 방법은 무엇입니까? (0) | 2020.07.04 |
MSBuild를 실행하면 SDKToolsPath를 읽을 수 없습니다. (0) | 2020.07.04 |
CONST를 PHP 클래스에서 정의 할 수 있습니까? (0) | 2020.07.04 |