windows programming(3)_oop 1 callection & string property system.string class datetime ...

26
Windows Programming(3)_OOP 1 Callection & String Callection & String Property System.String Class DateTime Collection ArrayList HashTable

Upload: tiffany-mckenzie

Post on 18-Jan-2016

233 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 1

Callection & StringCallection & String

Property System.String Class DateTime Collection ArrayList HashTable

Page 2: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 2

PropertyProperty 를 사용하지 않은 코드 …를 사용하지 않은 코드 …

class Address

{

protected string ZipCode;

public string GetZipCode() { return this.ZipCode; }

public void SetZipCode(string ZipCode) { this.ZipCode = ZipCode; }

}

Address addr = new Address();

addr.SetZipCode(“11111”);

String zip = addr.GetZipCode();

PropertyProperty

Page 3: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 3

class Address

{

protected string zipCode;

public string ZipCode

{

get { return zipCode; }

set { zipCode = value; }

}

Address addr = new Address();

addr.ZipCode = “11111”;

String zip = addr.ZipCode;

PropertyProperty 를 사용한 코드 …를 사용한 코드 …

PropertyProperty

Page 4: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 4

PropertyProperty 메소드를 포함하고 있는 클래스의 필드 (Smart field) 공개된 필드에 대한 직접적인 접근의 위험성을 감소 정의

사용

Class Button{ private string text; //field public string Text //text 의 property, 필드 접근 {

get {return text;} //getter, 필드 값을 readset {text = value} //setter. 필드에 값을 write

}} 예약된 키워드

Button b = new Button();

b.Text=“OK “; //setter 호출

string s = b.Text; //getter 호출

Page 5: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 5

//Property 예 (PropertyEx.cs)class Person{

private int age;public int Age // Property for the age.{

get {Console.WriteLine("getter call :" + age);return age;

}set {

Console.WriteLine("setter call :" + value);if (value > 0 && value <= 200)

age = value;else

Console.WriteLine(value + " is not age");}

}}class ProperyEx{ public static void Main() {

Person p1 = new Person();p1.Age = 20; //setter 호출Console.WriteLine("p1.age = "+ p1.Age); //getter 호출Console.WriteLine("-----------------"); p1.Age ++; //setter, getter 호출

Console.WriteLine("p1.age = " + p1.Age); //getter 호출 p1.Age = -1; //setter 호출 Console.WriteLine("p1.age = " + p1.Age); //getter 호출 }}

setter call : 20getter call : 20p1.age =20-------------getter call : 20setter call : 21getter call : 21p1.age =21setter call : -1-1 is not agegetter call : 21p1.age =21

Page 6: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 6

System.String ClassSystem.String Class

Unicode data list System.String = string Reference type Indexer 를 사용하여 문자열의 각 요소에 접근가능 string 은 수정이 불가능한 Immutable class

string s1 = "Hello";

System.String s2 = ”Spring”;

String s3 = new string(” 안녕” ); // Compile error , 문자열 매개변수 생성자 X

char []ch = {‘ 한’ ,’ 림’ };

string s4 = new string(ch); // 문자배열 매개변수 생성자로 문자열 생성

Console.WriteLine(“ 첫문자 ={0}”, s3[0]); // 인덱서를 이용한 문자열 요소접근

s1[0] = 'c'; // Compile error, 변경 불가능

Page 7: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 7

String String MembersMembers

Static field• Empty : empty string (string s = String.Empty)

Operator• [ ] (Brackets) : 문자열 요소 접근 (char a = s[0])• + 연산자 : 문자열 결합 (str = “ 가” + “,”+ ” 나” +”\ t” +” 다” )

Property • Length : 문자열 길이

Static methods• Copy() : 문자열 복사 public static string Copy(string);• Concat() : 문자열결합

public static string Concat(string1, string2, …);

string s1 = “ 하늘”;

string s2 = String.Copy(s1);

string s3 = String.Concat(s1,s2);

Page 8: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 8

Instance methods• Trim, TrimStart, TrimEnd : 공백 문자열 삭제• ToUpper , ToLower : 대 / 소문자 변환• Repalce ( 찾을 문자 , 바꿀 문자 ) : 문자열 치환• IndexOf ( 찾을 문자열 ) : 문자열 검색• Substring ( 시작위치 , 개수 ) : 문자열 추출• Insert( 시작위치 , 문자열 ) : 문자열 삽입• Remove ( 시작위치 , 개수 ) : 문자열 지우기• ToCharArray() : 문자열을 문자 배열로 변환• Split( 구분자 ) : 구분자로 문자열 분리 후 문자열 배열 반환

String String MembersMembers

string s = “ 물 : 불 : 흙 : 나무”;

string [] r = s.Split(‘:’); r“ 물”

“ 불”“ 흙”

“ 나무”

Page 9: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 9

//String methods 예 (StringSpriteEx.cs)string str1 = "dot,net:c# examples";string[] strs1 = str1.Split(',');string[] strs2 = str1.Split();//== string[] strs2 = str1.Split(null);char[] sp = {',', ':'};string[] strs3 = str1.Split(sp);

Console.WriteLine("str1 : " + str1);

Console.WriteLine("\n#str1.Split(',') : ");foreach (string str in strs1)

Console.WriteLine(str);

Console.WriteLine("\n#str1.Split(null) : ");foreach (string str in strs2)

Console.WriteLine(str);

Console.WriteLine("\n#str1.Split(sp) : ");foreach (string str in strs3)

Console.WriteLine(str);

str1 : dot,net:c# examples

#str1.Split(',') :dotnet:c# examples

#str1.Split(null) :dot,net:c#examples

#str1.Split(sp) :dotnetc# examples

Page 10: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 10

String ComparisonsString Comparisons Equals Method

• 문자열의 값이 같은지 비교• ==, != • public bool Equals ()• public static Equals(string, string)

Compare Method• 사전식 순서 , 대소문자 구분 없이 비교 가능

public static int Compare(string, string, bool);

string name1 = “ 하늘” ;string name2 = “ 하늘” ;if (name1.Equals(name2)); //trueif (String.Equals(name1, name2)); //trueif (name1 != name2); //false

int r = String.Compare(name1, name2, true);If (r == 0) //name1==name2If (r < 0) //name1 < name2If (r > 0) //name1 > name2

Page 11: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 11

//ID 입력 password 찾기 (StringTest)string [,] user={{"kim","kim123"}, {"lee", "lee123"}, {"min","min123"}};string id = " ";string pwd = " ";string cont = "Y";bool find = false;

while (true){Console.Write(" 찾을 ID 입력 : ");find = false;id = Console.ReadLine();for (int i=0; i < user.GetLength(0) ; i++){

if (String.Compare(user[i,0],id,true) == 0) // 대 , 소 구분 없이 같은 문자열 검색

{find= true; pwd = user[i,1]; break;

}}if (find)

Console.WriteLine("=> password: {0}", pwd);else

Console.WriteLine(" 찾는 id 가 없습니다 .");

Console.Write(" 계속하시겠습니까 (Y/N) : ");cont = Console.ReadLine();

if (cont.ToUpper() == "N") // 대문자로 변환하여 검색break;

}

찾을 ID 입력 : jin

찾는 id 가 없습니다 .

계속하시겠습니까 (Y/N) : y

찾을 ID 입력 : MIN

=> password: min123

계속하시겠습니까 (Y/N) : y

찾을 ID 입력 : lee

=> password: lee123

계속하시겠습니까 (Y/N) : n

Page 12: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

12

DateTimeDateTime

날짜와 시간을 다룰 수 있는 구조체 여러 형식의 날짜 저장 가능 ( 생성자 오버로딩 )

//DateTime 생성 및 출력 예 System.DateTime dateTime = new System.DateTime(

1979, // Year 07, // Month 28, // Day 22, // Hour 35, // Minute5, // Second 15 // Millisecond );

System.Console.WriteLine("{0:F}", dateTime); System.Console.WriteLine("{0}", dateTime);

System.DateTime dteMyBirthday = new System.DateTime(1969,7,22); System.Console.WriteLine("dteMyBirthday: {0}", dteMyBirthday.ToString());

DateTime dteToday = DateTime.Today; // 시스템의현재날짜추출 dteToday = DateTime.Now; // 시스템의현재시간추출 Console.WriteLine("ToLongTimeString : {0}", dteToday.ToLongTimeString()); Console.WriteLine("ToString : {0}", dteToday.ToString());

Page 13: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 13

날짜의 일부분 추출하기날짜의 일부분 추출하기

DateTime 의 속성 (Month, Day, Hour, Minute, Second)을 이용하여 날짜의 일부분 추출 // 날짜 일부 추출 예

System.DateTime moment = new System.DateTime( 1999, 1, 13, 3, 57,

32, 11);

int year = moment.Year; // Year gets 1999.

int month = moment.Month; // Month gets 1 (January).

int day = moment.Day; // Day gets 13.

int hour = moment.Hour; // Hour gets 3.

int minute = moment.Minute; // Minute gets 57.

int second = moment.Second; // Second gets 32..

int millisecond = moment.Millisecond; // Millisecond gets 11

Page 14: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 14

CollectionCollection

Objects 의 집합 System.Collections

• Arraylist, BitArray, HashTable, Queue, Stack 등과 같은 다양한 개체 컬렉션을 정의하는 클래스와 인터페이스를 포함

Collection 을 위한 공통의 인터페이스로 일관성 유지• IEnumerable : collection 안의 항목을 하나씩 접근할 수 있는

기능제공 (foreach 사용 허용 )

• ICollection(IEnumerable 상속 ) : collection 의 크기 , 복사기능 제공

• IList(IEnumerable, ICollection 상속 ) : 인덱스로 항목들의 목록을 관리할 수 있는 기능 제공 (ArrayList)

• IDictonary(IEnumerable, ICollection 상속 ) : 키 값으로 항목들의 목록을 관리할 수 있는 기능제공 (HashTable)

Page 15: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 15

ArrayListArrayList

List of Objects 순서를 가지며 중복허용 인덱스로 항목 접근 가능하도록 배열 안에 데이터 저장 배열크기가 가변적 리스트의 항목들을 추가 , 삽입 , 삭제 가능

using System.Collections;

class Department{ ArrayList employees = new ArrayList(); ...}

Page 16: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 16

ArrayList membersArrayList members

public class ArrayList : IList, ICloneable{ int Add (object value) ... void Insert(int index, object value) ...

void Remove (object value) ... void RemoveAt(int index) ... void Clear () ...

bool Contains(object value) ... int IndexOf (object value) ...

object this[int index] { get... set.. }

int Capacity { get... set... } void TrimToSize() ... ...}

control of memoryin underlying array

add new elements

remove

containment testing

read/write existing element

Page 17: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 17

ArrayList indexerArrayList indexer

0~count-1 범위의 리스트 요소 접근에 이용

ArrayList a = new ArrayList();a.Add("bbb");a.Add("aaa");a.Add("ddd");

a[2] = "ccc";

string s = (string)a[2];

use Add to addnew elements

change existing element

read existing element

Page 18: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 18

ArrayList CapacityArrayList Capacity

리스트 생성시 용량 설정 (default 16) 용량 부족 시 자동으로 증가 Get/set property

ArrayList a = new ArrayList();ArrayList b = new ArrayList(50);

b.Capacity = 100;

int c = b.Capacity;

default capacity is 16

specify capacity of 50

set capacity to 100

get capacity

Page 19: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 19

//book 객체를 리스트로 관리하기 위한 예using System;using System.Collections;class Book //Book class 정의 { string kind; string title; string author; public Book(string kind, string title, string author) {

this.kind = kind;this.title = title;this.author = author;

} public override string ToString() {

return (kind+"\t"+title +"\t"+author); }}

ArrayList ArrayList 사용 예 사용 예

Page 20: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 20

//Arraylist 이용하여 booklist 처리 public class BookList { public static void Main() { ArrayList booklist = new ArrayList(); booklist.Add(new Book(" 비소설 ", " 선물 "," 스펜서존슨 ")); //arraylist 에 요소 추가 booklist.Add(new Book(" 소설 ", " 나무 "," 베르나르베르베르 ")); booklist.Add(new Book(" 소설 ", " 길 "," 조창인 ")); booklist.Add(new Book(" 경제경영 ", " 메모의기술 "," 사카토켄지 "));

Console.WriteLine( "booklist" ); Console.WriteLine( "\tCount: {0}", booklist.Count ); // 실제 요소의 개수 Console.WriteLine( "\tCapacity: {0}", booklist.Capacity ); // 용량

Console.WriteLine( "Kind\tTitle\tAuthor" ); foreach(Book b in booklist) // 모든 구성 요소들을 반복하여 접근

Console.WriteLine( "{0}", b); }}

booklist Count: 4 Capacity: 16Kind Title Author비소설 선물 스펜서존슨소설 나무 베르나르베르베르소설 길 조창인경제경영 메모의기술 사카토켄지

Page 21: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 21

HashtableHashtable

중복되지 않는 키와 키에 대응되는 값 ( 객체 ) 를 가지는 형태 Key 와 value 에 해당하는 object 저장 Key 로 Value 를 접근하기 위한 indexer 제공

Hashtable ages = new Hashtable();

ages["Ann"] = 27;ages["Bob"] = 32;ages.Add("Tom", 15);

ages["Ann"] = 28;

int a = (int)ages["Ann"];

create

add

update

retrieve

Page 22: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 22

Hashtable traversalHashtable traversal

foreach 를 사용하여 해시테이블의 구성요소들을 순차적으로 접근 DictionaryEntry 구조를 이용하여 해시테이블의 Key 와 Value 를

접근Hashtable ages = new Hashtable();

ages["Ann"] = 27;ages["Bob"] = 32;ages["Tom"] = 15;

foreach (DictionaryEntry entry in ages){ string name = (string)entry.Key; int age = (int) entry.Value; ...}

enumerate entries

get key and value

Page 23: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

23

public class BookList { public static void Main() { Hashtable booklist = new Hashtable();

booklist.Add(1,new Book(" 비소설 ", " 선물 "," 스펜서존슨 ")); // 테이블에 구성요소 추가 booklist.Add(2,new Book(" 소설 ", " 나무 "," 베르나르베르베르 ")); booklist.Add(3,new Book(" 소설 ", " 길 "," 조창인 ")); booklist.Add(4,new Book(" 경제경영 ", " 메모의기술 "," 사카토켄지 "));

Console.WriteLine( "booklist" ); Console.WriteLine( "\tCount: {0}", booklist.Count );

//(1) DictionaryEntry 구조로 테이블의 구성요소 반복 접근 foreach (DictionaryEntry entry in booklist) {

int num = (int)entry.Key; Book b = (Book)entry.Value; Console.WriteLine( "{0}", b);

} //(2)IDictionaryEnumerator 이용 , 테이블 구성요소 반복 접근 IDictionaryEnumerator bE = booklist.GetEnumerator(); while ( bE.MoveNext() )

Console.WriteLine("{0}:{1}", bE.Key, bE.Value);

//(3) key 값들을 집합으로 얻어서 key 들을 인덱스로 하여 value 접근 ICollection bk= booklist.Keys; foreach(int k in bk) Console.WriteLine("{0}:{1}",k, booklist[k]); }}

Page 24: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 24

연습문제 연습문제

1. ID 로 Password 를 찾는 문제를 Hashtable 을 사용하여 해결하세요 .< 처리조건 >(1) 윈도우어플리케이션으로 작성(2)ID 를 입력하여 찾기 버튼을 누르면 해시테이블에서 검색하여 검색 결과 출력

Page 25: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 25

2. 급여관리 프로그램 작성 : WinPG2_CSharp.ppt 의 연습문제 (1) 수정(1)Employee 구조체를 클래스로 변경

구성요소 : 사원명 (name), 가족수 (family), 작업시간 (hour), 급여 (pay) 생성자 선언

– 사원명 , 가족수 , 작업시간을 매개변수로 받아서 구성요소 초기화– 가족수 , 작업시간으로 급여 (pay) 계산 급여 = ( 가족수 * 50000) + ( 작업시간 * 20000)

사원명 , 급여에 대한 readonly-property 정의(2)ArrayList 를 이용하여 Employee 의 리스트 구성

확인버튼을 등록버튼으로 변경하여 등록버튼을 누르면 입력된 값을 Employee 객체로 생성하여 리스트에 추가

(3) 리스트 출력을 위한 버튼 추가 리스트출력버튼 : 클릭하면 Employee 리스트를 라벨에 출력 (foreach)

(4) 리스트 출력 수정 리스트박스 컨트롤 추가 (listBox1) 리스트박스에 Employee 리스트를 추가 (listBox1.items.Add())

(5) 프로그램 결과화면

Page 26: Windows Programming(3)_OOP 1 Callection & String  Property  System.String Class  DateTime  Collection  ArrayList  HashTable

Windows Programming(3)_OOP 26

TextBox control

Employee Object

name

family

hour

pay

User Interface Control

ListBox control

Employee List