2011. 4. 3. 13:45

KeyValuePair<TKey, TValue> Structure

Defines a key/value pair that can be set or retrieved.

Type Parameters

TKey

The type of the key.

TValue

The type of the value.


이번에 처음으로 ASP.NET + C# 을 사용해서 프로젝트를 진행하면서 이런저런 어려움이 많습니다.
주 언어가 C++이다 보니 생각이 그 범위에서 완전히 벗어나기 어렵기도 하구요. ^-^;

여튼 C#에서 STL의 pair 와 같은 역할을 하는게 없나해서 찾아보니 KeyValuePair 가 있더군요.
사용법은 pair와 동일합니다.

MFC(C++) : std::pair<CString,CString>
C#            : KeyValuePair<string,string>

MFC(C++)

* 참고
foreach 문은 공식적으로 C++ 에서 지원되지 않습니다. 다만, Visual Studio Dev. Tool 에서 지원해주는 것입니다.
가끔 이걸 헷갈리시는 분들이 있더군요. 여기 예시에서는 편의를 위해 foreach를 사용했습니다.

for each( std::pair<CString,CString> kvp in myPairList)
{
    printf("Key = %s, Value = %s", kvp.first, kvp.second);
}

C#

foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

더 자세한 내용은 msdn 을 참고하시면 되겠습니다.
http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx


* 직접 짜는 수고(?)를 덜기 위해 Stack Overflow 에 올라온 클래스를 같이 적어 놓습니다.

public class Pair<T, U> { 
   
public Pair() { 
   
} 
 
   
public Pair(T first, U second) { 
       
this.First = first; 
       
this.Second = second; 
   
} 
 
   
public T First { get; set; } 
   
public U Second { get; set; } 
}; 

출처 : http://stackoverflow.com/questions/166089/what-is-c-analog-of-c-stdpair
Posted by 나이스곰