2. OBJECTIVE.
예제를 통해 C# 코드를 이해 함으로써, 다른 C#코드
를 볼 때 이해 할 수 있도록 하기 위한 자료.
특정 기능들의 틀 부분만 설명.
기존 언어들과 다른 문법과 새로운 기능 위주로 설명.
3. HELLO WORLD ?
Using System;
Namespace classname
{
class Program
{
public void main(String[] args)
{
Console.WriteLine(“Hello World!”);
}
}
}
4. NAME SPACE
Using System;
- C++의 namespace와 같은 개념.
- System class의 메소드를 사용 가능하게 해준다.
- C 의 include<stdio.h> Java의 import와 같은 개념.
- Using을 통해 C#에서 제공하는 클래스를 활용 할 수
있다.
Ex) Console.WriteLine(“Hello World!”);
Namespace를 선언 하지 않았다면
>> System.Console.WriteLine(“Hello World!”);
5. CONSOLE.WRITELINE
int a = 10;
float b = 2.5f;
String c = “Hello World”;
Printf(“%d %f %s”, a, b, c);
Console.WriteLine(“first parm is {0}, second is {1}, else
{2}”, a, b, c);
- 데이터 타입을 %로 설정 할 필요 없이 자동으로 그 타입
에 맞게 바인딩 되어 출력한다.
※ 입력은 변수 = Console.ReadLine(); 로 할 수 있다.
6. FOR EACH
Int[] values = {1, 2, 3, 4, 5};
Foreach(int a in values)
{
Console.WriteLine(a);
}
7. REF
public static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int a = 3;
int b = 4;
Swap(ref a, ref b);
}
8. OUT
public static void Swap(out int a, out int b)
{
//error
//int temp = a;
//a = b;
//b = temp;
}
static void Main(string[] args)
{
int a = 3;
int b = 4;
Swap(ref a, ref b);
}
9. OUT VS REF
공통점 : 둘 다 참조에 의한 매개변수 전달
차이
-ref : 변수에 반드시 초기값을 주어야 한다.
-out : out변수를 r-value로 주지 못한다.
뒤에 코드 error 고친다면
a = (out이 아닌 다른 변수나 상수 값); //b either
10. 가변길이 매개변수
Public static float GetAverage(params float[] args)
{
float mean = 0;
for(int i=0; i<args.Length; i++)
{
mean += args[i];
}
return mean / args.Length;
}
Public static void Main()
{
float result = GetAverage(177.3f, 172.1f, 165.3f);
Console.WriteLine(“The Average {0} cm”, result);
}
11. 상속 그리고 오버라이딩
Class Child : Parent 의 형식
함수 재정의 종류
1. new 키워드 이용.
2. virtual, overide 키워드 이용.
- New : 상위 클래스 함수 완전 무시(Hiding)
- Overide : 상위 클래스에서 virtual로 표시된 함수 재
정의
12. 오버라이딩 예제(NEW)
Class Shape
public void Draw()
Console.WriteLine(“Shape method!”);
Class Triangle : Shape
public new void Draw()
Console.WriteLine(“Triangle method!”);
base.Draw();
Class NewBase
public static void Main()
Shape s = new Shape();
s.Draw();
Triangle t = new Triangle();
t.Draw();
14. 오버라이딩 예제2 (OVERIDE, ABSTRACT 연산
자)
Abstract class Computer
public abstract void Network();
public void Graphic()
Console.WriteLine(“Graphic OK.”);
Class NewComputer : Computer
public override void Network()
Console.WriteLine(“Network OK.”);
Class Override
public static void Main()
Computer c = new NewComputer();
c.Graphic();
c.Network();
16. 오버라이딩 예제3 (OVERIDE, VIRTUAL 연산
자)
class Compute
public void Graphic()
Console.WriteLine("Graphic OK.");
public virtual void Network()
Console.WriteLine("base Network OK");
class NewComputer : Computer
public override void Network()
Console.WriteLine("derived Network OK.");
class Program
public static void Main(string[] args)
Computer c = new Computer();
c.Graphic();
c.Network();
Computer n = new NewComputer();
n.Graphic();
n.Network();
18. 상수 선언
Class의 맴버 변수로 선언한다면 ..
- Public const float PI = 3.14;
>> 무조건 처음에 초기화 해주어야 한다.
(컴파일 할 때 값이 결정 된다.)
- Public readonly float PI;
생성자()
{
this.PI = 3.14;
}
>> 인스턴스가 생성될때 값을 정할 수 있다.
19. IS, AS 연산자
Is 연산자 : T/F 반환
As 연산자 : T일경우 해당하는 클래스 명 반환
사용법 : 문장 is/as 비교할자료형.
ex) Interface 포유류
class 고양이과 : 포유류
class 사자 : 포유류, 고양이과
포유류 simba = new 사자();
//simba is/as 고양이과?
고양이과 leo = new 고양이과();
//leo is/as 사자?
21. 분할 클래스
한 클래스를 여러 번에 나누어서 구현 할 수 있다.
Partial class classname
{
Method1(){}
}
Partial class classname
{
Method2(){}
}
22. 배열 그리고 컬렉션
배열의 선언 형태는 자바와 비슷하다.
자바와 같이 C#에서도 다양한 배열의 구조적/기능적
인 한계를 보완하는 자료구조를 제공하고 있다.
ArrayList, HashTable과 같은 기능을 제공하며
Using System.Collections를 선언해서 사용할 수
있다.
- 사용 방법은 C# API 참조
23. 속성(PROPERTY)
- Property는 클래스나 데이터의 필드에 접근해서 값을 저장하거나 읽어오는
데 사용하는 요소.
- Attribute는 코드를 설명하기 위해 사용되는 요소.
Class NameCard
private string name;
public void setName(string name)
public string Name
{
get{return name;}
set{name = value;}
}
NameCard myCard = new NameCard();
myCard.Name = “최길우”//set
Console.WriteLine(myCard.Name);//get
24. 인덱서(INDEXER)
속성 : 맴버필드 접근
인덱서 : 배열에 접근
Private string[] name;
Public string this[int i]
{
get{return name[i];}
set{name[i] = value;}
}
Name[0] = “김제민”;
Name[1] = “최길우”;
Console.WriteLine(Name[0]);
…
속성과 인덱서 : 클래스나 객체의 데이터를 안전하게 읽고 쓸 수 있는 메커니
즘.
25. DELEGATE(델리게이트)
뜻 : 대리자, 즉 다른 method에 대한 참조를 가지고 있다
가 델리게이트를 호출하면 자신이 참조하고 있는 메소드
실행.
함수를 캡슐화 해서 호출, C언어의 함수포인터 개념과 비
슷하며 이벤트나 쓰레드를 통해서 많이 사용한다.
Public delegate void PrintOut(String s); //델리게이트 선언
Public static void WriteToConsole(String s)
{
Console.WriteLine(s);
}
PrintOut print = new PrintOut(WriteToConsole);
print(“PrintOut 호출 >> 다시 WriteToConsole 호출”);
26. 델리게이트 익명 메소드
//선언
Public delegate void PrintOut(String s);
//정의
PrintOut print = delegate(string s)
{
Console.WriteLine(s);
}
Print(“Anonym-method is very simple, isn’t it?”);
27. 델리게이트의 합성
Public delegate void MyDelegate;
MyDelegate A,B,C,D;
A=new MyDelegate(SomeMethod);
B=new MyDelegate(SomeOther);
C=A+B;//A다음에 B실행
D=C-B;//A+B-B 즉 A만 실행
28. 이벤트
C#의 이벤트 처리는 델리게이트에 기반하고 있다.
-이유?
Event a = 마우스 누르고 손 떼지 않기(mouse pressed)
Event b = 마우스 누르고 손 떼기(mouse release)
Event c = 마우스 클릭(=a+b)
Evend d = c 두번.
29. 이벤트 예제
class Client
private int ID;
public delegate void ClientService(object sender, EventArgs args);
public event ClientService Service;
public Client(int ID) //constructor
this.ID = ID;
public int ClientID //Property
get { return this.ID; }
Public void FireEvent()
if(Service != null)
EventArgs args = new EventArgs();
Service(this, args);
30. 이벤트 예제 계속
Class MainApp
public static void OnEvent(object sender, Event Args args)
Client client = (Client)sender;
Console.WriteLine(“고객ID {0} : 경품 당첨”, client.ClientID);
public static void Main()
Client clientA = new Client(1);
clientA.Service += new Client.ClientService(OnEvent);
clientA.FireEvent();
32. ATTRIBUTE(특성), GENERIC(일반화)
코드 안의 요소(메소드, 속성, 필드 등)에 대한 설명
을 담는 객체.
런타임에도 읽을 수 있는 주석.
1. Obsolate
2. Conditional
3. DLL import
- 세가지 방법이 있으며 많이 사용하지 않으므로 자
세한 것은 C#서적 참조.
- C++, Java에서 제공하는 Templet과 비슷하므로 필
요할때 서적 참조
<class>
33. 파일 조작
Using System.IO
FileInfo fileInfo = new FileInfo(@“C:test.txt”);
If(fileInfo.Exists)
{
Console.WriteLine(fileInfo.Directory);
…
fileInfo.Name, Length..
}
파일조작에 대한 메소드나 속성은 MSDN 참조..
35. FILE I/O(STREAM) - READ
Using System.IO;
Using System.Text;
Stream stream = File.OpenRead(@”C:test.txt”);
StreamReader sr =
new StreamReader(stream, Encoding.Default);
String str;
Int i = 0;
While((str = stream.ReadLine()) != null)
{
i++;
Console.WriteLine(“Line {0}: {1}”, i, str);
}
Sr.Position = 0;
Str = streamReader.ReadLine();
Console.WriteLine(“Line {0} : {1}”, i, str);
sr.close();
36. FILE I/O(STREAM) - WRITE
Using System.IO;
Using System.Text;
StreamWriter sw =
new StreamWriter(@”C:test.txt”, true, Encoding.Default);
sw.WriteLine(“true = 내용 더하기”);
sw.close();
37. FILE I/O(STREAM) - BINARY
Using system.IO;
Using system.Text;
Stream stream = File.OpenWrite(@”C:test.txt”);
BinaryWriter bw = new BinaryWriter(stream);
Bw.Write(1004);
Stream.Close();
stream = File.OpenRead(@”C:test.txt”);
BinaryReader br = new BinaryReader(stream);
Int32 input = binaryReader.ReadInt32();
Console.WriteLine(input);
Stream.Close();
38. DB CONNECT
String strCnn;
MySqlConnection oCnn = null;
Try
strCnn = "data source=localhost;database=test; user
id=root;password=root";
oCnn = new MySqlConnection(strCnn);
oCnn.Open();
catch (MySqlException _e)
Console.WriteLine(_e.Message);
String squery = “select * from test;”;
…
Insert into test values( …)
39. DB CONNECT & HANDLE.
앞의 예제보다 최근에 코딩할 때는 Helper를 쓰는 경
향이 많다.
코드 수가 적고 편하기 때문에 ..
string strCnn = "data source=localhost;database=test; user
id=root;password=root";
string query = "insert into test values(23, "Chris");";
DataSet ds = MySqlHelper.ExecuteDataset(strCnn, query);
…