1) 아래 클래스의 핵심 method, 역할 등을 예제 위주로 정리해 주세요.
- ArrayList : 크기가 자유롭게 변하는 배열과 비슷한 컬렉션
ArrayList ItemList = new ArrayList();
// 추가
ItemList.Add("2"); // 2
ItemList.Add("1"); // 2 1
ItemList.Add("3"); // 2 1 3
// 삽입
ItemList.Insert(3, "4"); // 2 1 3 4
// 정렬
ItemList.Sort(); // 1 2 3 4
// 삭제
ItemList.Remove("3"); // 1 2 4
ItemList.RemoveAt(1); // 1 4
- Hashtable : Key, value로 이루어진 컬렉션, Key가 추가되어 빠른 검색 속도를 자랑한다.
// 추가
ht.Add("key1", "add"); // "key1" : "add",
ht.Add("key2", "remove"); // "key1" : "add", "key2" : "remove"
ht.Add("key3", "update"); // "key1" : "add", "key2" : "remove", "key3" : "update"
ht.Add("key4", "search"); // "key1" : "add", "key2" : "remove", "key3" : "update", "key4" : "search"
// 삭제
ht.Remove("key3"); // "key1" : "add", "key2" : "remove", "key4" : "search"
// 변경
ht["key2"] = "delete"; // "key1" : "add", "key2" : "delete", "key4" : "search"
// 검색
if (ht.ContainsValue("add"))
Console.WriteLine("Find"); // Find
else
Console.WriteLine("Not find");
// 출력
foreach (var item in ht)
Console.WriteLine(item.Key + " : " + item.Value); // "key1" : "add", "key2" : "delete", "key4" : "search"
2) 아래 용어를 설명해주세요.
- Boxing : 값 형식을 참조 형식으로 변환하는 것
- Unboxing : 참조 형식을 값 형식으로 변환하는 것
- Generic : 이전 글 참조
Boxing/Unboxing은 내부적으로 메모리 할당과 객체생성 및 형 변환 과정으로 인해 성능저하가 발생한다.
3) 아래 클래스의 핵심 method, 역할 등을 예제 위주로 정리해 주세요.
- List : ArrayList와 같은 기능을 하며, 로 타입을 지정하여 사용하여야 한다. 제네릭(generic)으로 구현되어 있으며, 지정한 타입 외에는 담을 수 없다.
List<string> list = new List<string>();
// 추가
list.Add("2"); // 2
list.Add("1"); // 2 1
list.Add("3"); // 2 1 3
// 삽입
list.Insert(3, "4"); // 2 1 3 4
// 정렬
list.Sort(); // 1 2 3 4
// 삭제
list.Remove("3"); // 1 2 4
list.RemoveAt(1); // 1 4
- Dictonary : HashTable과 같은 기능을 하며, 로 타입을 지정하여 사용하여야 한다. 제네릭(generic)으로 구현되어 있으며, 지정한 타입 외에는 담을 수 없다.
Dictionary<string, string> dict = new Dictionary<string, string>();
// 추가
dict.Add("key1", "add"); // "key1" : "add",
dict.Add("key2", "remove"); // "key1" : "add", "key2" : "remove"
dict.Add("key3", "update"); // "key1" : "add", "key2" : "remove", "key3" : "update"
dict.Add("key4", "search"); // "key1" : "add", "key2" : "remove", "key3" : "update", "key4" : "search"
// 삭제
dict.Remove("key3"); // "key1" : "add", "key2" : "remove", "key4" : "search"
// 변경
dict["key2"] = "delete"; // "key1" : "add", "key2" : "delete", "key4" : "search"
// 검색
if (dict.ContainsValue("add"))
Console.WriteLine("Find"); // Find
else
Console.WriteLine("Not find");
// 출력
foreach (var item in dict)
Console.WriteLine(item.Key + " : " + item.Value); // "key1" : "add", "key2" : "delete", "key4" : "search"
4) ObservableCollection 클래스의 특징 및 용도를 설명해 주세요.
ObservableCollection은 컬렉션에 변경이 발생하면 등록된 콜백이 호출되는 컬렉션이다.
일반적으로 윈도우 컨트롤과 바인딩하여 데이터 변경에 대한 처리 용도로 사용된다.
private static void listBoxCollectionCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Console.WriteLine(e.Action);
}
static void Main(string[] args)
{
ObservableCollection<string> listBoxCollection = new ObservableCollection<string> { "item1", "item2", "item3" };
listBoxCollection.CollectionChanged += listBoxCollectionCollectionChanged;
foreach (var listBoxItem in listBoxCollection)
{
Console.WriteLine(listBoxItem);
}
listBoxCollection.Add("item4");
listBoxCollection.Remove("item1");
listBoxCollection.Move(0, 1);
}
5) IEnumerable 인터페이스의 특징 및 용도를 확인해 주세요.
IEnumerable
인터페이스는 GetEnumerator
메서드만 포함하고 있으며, 이 메서드는 IEnumerator<T>
을 반환한다.
IEnumerator
메서드와 프로퍼티
-
MoveNext() : 컬렉션에 요소를 순방향으로 순회하는 메서드
-
Reset() : 커서를 컬렉션의 첫번째 요소 앞의 초기위치로 설정하는 메서드
-
Current : 현재 요소를 가리키는 프로퍼티
사용자 정의 클래스에서 foreach
구문을 통해 요소를 열거하려면 IEnumerable
과 IEnumerator
인터페이스에 정의된 메서드를 구현해야 한다.
요소를 열거하는 foreach
는 내부적으로 IEnumerable 인터페이스를 통해 IEnumerator를 사용하는 것을 볼 수 있다.
E enumerator = (collection).GetEnumerator();
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
statement;
}
}
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
}
6) DateTime 클래스의 기본 사용법을 정리해 주세요.
// 지금 시각, 오늘, 어제, 내일 날짜
Console.WriteLine(DateTime.Now);
Console.WriteLine(DateTime.Now.ToShortDateString());
Console.WriteLine(DateTime.Now.AddDays(-1).ToShortDateString());
Console.WriteLine(DateTime.Now.AddDays(1).ToShortDateString());
// 문자열 서식
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone
// 표준 문자열 서식
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime
7) String 클래스의 기본 사용법을 정리해 주세요.
// 문자열 더하기
string s1 = "Hello";
string s2 = "World!";
string s3 = s1 + " " + s2;
Console.WriteLine(s3); // Hello Wolrd!
// 문자열 검색
int idx = s3.IndexOf("World");
Console.WriteLine(idx); // 6
// 일부 문자열 잘라내기
string s4 = s3.Substring(idx, 6);
Console.WriteLine(s4); // World!
// 문자열 Trim
s4 = " " + s4;
Console.WriteLine(s4.Trim()); // World!
// 문자열 replace
s4 = s4.Trim();
Console.WriteLine(s4.Replace("!", " Hello!")); // World Hello!
// 문자 -> 숫자 변환
Console.WriteLine(int.Parse("123")); // 123
Console.WriteLine(int.Parse("123").GetType()); // System.Int32
// 숫자 -> 문자 변환
Console.WriteLine(123.ToString()); // 123
Console.WriteLine(123.ToString().GetType()); // System.String
문자열 서식출력
- System.Text.StringBuilder : 문자열 조합 시 사용
- System.Text.Encoding : 문자 인코딩 변환 시 사용
- System.Text.RegularExpressions.Regex : 정규표현식 문자열 처리 시 사용
8) 파일 관련 질문입니다. 아래 기능은 어떻게 구현하면 되나요?
// 텍스트 파일에 쓰기
using (FileStream fs = File.Open("test.log", FileMode.Create))
{
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.WriteLine("Hello World");
sw.WriteLine("Anderson");
sw.Flush();
}
// 텍스트 파일 한번에 한줄씩 읽기
using (FileStream fs = File.Open("test.log", FileMode.Open))
{
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
string text1 = sr.ReadLine();
}
// 텍스트 파일 한번에 다 읽기
using (FileStream fs = File.Open("test.log", FileMode.Open))
{
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
string text = sr.ReadToEnd();
}
// File 클래스 사용 - 파일 전체 읽기
string text2 = File.ReadAllText("test.log");
// File 클래스 사용 - 파일 전체 쓰기
File.WriteAllText("test2.log", "Hello World\r\nAnderson\r\n");
// File 클래스 사용 - 파일 한줄씩 쓰기
string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines("test3.log", lines);
가비지 컬렉터
***가비지 컬렉터(Garbage Collector)***는 힙에 할당된 메모리를 자동으로 해제하고 관리하는 기능이다.
GC는 할당된 메모리를 세대(generation)로 구분하고 수집이 필요한 시점에 참조 여부를 판단하여 메모리를 재조정한다.
세대별 구분
- 0 세대 : 최근에 생성된 객체
- 1 세대 : 0세대 수집 시 해제되지 않은 객체
- 2 세대 : 1세대 수집 시 해제되지 않은 객체
대용량 객체 힙(Large Object Heap) : 객체 크기가 85,000 이상인 경우에 사용되는 힙 공간. LOH에 생성된 객체는 초기부터 GC 2세대에서 관리된다.
Boxing/Unboxing
http://www.mkexdev.net/Article/Content.aspx?parentCategoryID=1&categoryID=5&ID=671
가비지 컬렉터
https://msdn.microsoft.com/ko-kr/library/67C5A20D-1BE1-4EA7-8A9A-92B0B08658D2.aspx
https://www.microsoft.com/korea/msdn/netframework/using/documentation/ms973837.aspx
http://m.dbguide.net/about.db?cmd=view&boardConfigUid=19&boardUid=151230
http://www.simpleisbest.net/post/2011/04/01/Review-NET-Garbage-Collection.aspx