'Programming > Data Structure' 카테고리의 다른 글
[자료구조] 연결리스트(Linked List) (0) | 2016.02.02 |
---|
[자료구조] 연결리스트(Linked List) (0) | 2016.02.02 |
---|
[자료구조] 스택과 큐(Stack & Queue) (0) | 2016.02.02 |
---|
파일 입출력 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System; using System.IO; namespace EX14_FILEIO { class MainClass { public static void Main (string[] args) { string path = @"D:\Lectures\C#\Examples\EX14_FILEIO\MyTest.txt"; if (!File.Exists(path)) { // 파일 생성 후 쓰기 using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("My"); sw.WriteLine("First"); sw.WriteLine("TextFile"); } } // 파일 읽기 using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } } } | cs |
바이너리 파일 입출력 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | using System; using System.IO; namespace EX14_FILEIO_BINARY { class MainClass { private const string FILE_NAME = "highscore.dat"; public static void WriteValues() { using (BinaryWriter bw = new BinaryWriter(File.Open(FILE_NAME, FileMode.Create))) { bw.Write("설인범"); bw.Write(5000); bw.Write(10); bw.Write(true); } } public static void DisplayValues() { string name; int highscore; int stage; bool item; if (File.Exists(FILE_NAME )) { using (BinaryReader br = new BinaryReader(File.Open(FILE_NAME, FileMode.Open))) { name = br.ReadString(); highscore = br.ReadInt32(); stage = br.ReadInt32(); item = br.ReadBoolean(); } Console.WriteLine("플레이어 : " + name); Console.WriteLine("최고점수 : " + highscore); Console.WriteLine("스테이지 : " + stage); Console.WriteLine("아이템사용 : " + item); } } public static void Main (string[] args) { WriteValues(); DisplayValues(); } } } | cs |
디렉터리 파일 검색 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | using System; using System.IO; using System.Linq; namespace EX14_FILEIO_DIRECTORY { class MainClass { public static void Main (string[] args) { try { var files = from file in Directory.EnumerateFiles(@"D:\Lectures\C#\Examples\", "*.*", SearchOption.AllDirectories) from line in File.ReadLines(file) where line.Contains("EX") select new { File = file, Line = line }; foreach (var f in files) { Console.WriteLine(f.File); } Console.WriteLine("{0} files found.", files.Count().ToString()); } catch (UnauthorizedAccessException UAEx) { Console.WriteLine(UAEx.Message); } catch (PathTooLongException PathEx) { Console.WriteLine(PathEx.Message); } } } } | cs |
파일 스트림 입출력 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | using System; using System.IO; using System.Collections.Generic; namespace EX14_FILEIO_STREAM { class Score { public string Name { get; set; } public int HighScore { get; set; } } class MainClass { private const string FILE_NAME = @"Score.txt"; private static List<Score> scores; private static void InitScoreList() { scores = new List<Score> (); scores.Add (new Score () { Name = "홍길동", HighScore = 3000 }); scores.Add (new Score () { Name = "임꺽정", HighScore = 2500 }); scores.Add (new Score () { Name = "장길산", HighScore = 2000 }); scores.Add (new Score () { Name = "설인범", HighScore = 1500 }); scores.Add (new Score () { Name = "도둑넘", HighScore = 1000 }); } private static void WriteScore() { // StreamWriter를 이용하여 파일 출력 using (StreamWriter sw = new StreamWriter(FILE_NAME)) { foreach(Score s in scores){ sw.WriteLine("{0} : {1}", s.Name,s.HighScore); } } } private static void ReadScore() { FileStream fsIn = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read); // StreamReader를 이용하여 파일 스트림으로 부터 데이터를 읽는다. using (StreamReader sr = new StreamReader(fsIn)) { string input; while (sr.Peek() > -1) { // 파일 스트림이 끝날때 까지 input = sr.ReadLine(); Console.WriteLine(input); } } } public static void Main (string[] args) { InitScoreList(); WriteScore (); ReadScore (); } } } | cs |
Serialization 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; namespace EX14_FILEIO_Serialization { [Serializable] public class Score { public string Name { get; set; } public int HighScore { get; set; } } class MainClass { private const string FILE_NAME = @"Score.dat"; private static List<Score> scores; private static void InitScoreList() { scores = new List<Score> (); scores.Add (new Score () { Name = "홍길동", HighScore = 3000 }); scores.Add (new Score () { Name = "임꺽정", HighScore = 2500 }); scores.Add (new Score () { Name = "장길산", HighScore = 2000 }); scores.Add (new Score () { Name = "설인범", HighScore = 1500 }); scores.Add (new Score () { Name = "도둑넘", HighScore = 1000 }); } public static void Serialize() { FileStream fs = new FileStream(FILE_NAME, FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, scores); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } public static void Deserialize() { scores = null; // Open the file containing the data that you want to deserialize. FileStream fs = new FileStream(FILE_NAME, FileMode.Open); try { BinaryFormatter formatter = new BinaryFormatter(); scores = (List<Score>) formatter.Deserialize(fs); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { fs.Close(); } foreach (Score s in scores) { Console.WriteLine("{0} : {1}", s.Name, s.HighScore); } } public static void Main (string[] args) { InitScoreList(); Serialize (); Deserialize (); } } } | cs |
[C# 프로그래밍] 13장 애트리뷰트 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 12장 리플렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 11장 람다식 (0) | 2016.01.11 |
[C# 프로그래밍] 10장 LINQ (0) | 2016.01.11 |
[C# 프로그래밍] 9장 델리게이트와 이벤트 (0) | 2016.01.11 |
애트리뷰트 생성 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true)] public class Author : System.Attribute { public string Name { get; set; } public double Version { get; set; } public Author(string name) { Name = name; Version = 1.0; } } namespace EX13_Attribute { [Author("Admin", Version = 1.5)] [Author("Hyunseok Oh", Version = 1.1)] class Enemy { } class MainClass { public static void Main (string[] args) { Enemy enemy = new Enemy (); object[] attrs = enemy.GetType ().GetCustomAttributes (true); foreach (Author attr in attrs) { Console.WriteLine("Class {0} Version {1} made by {2} ", enemy.GetType().Name, ((Author)attr).Version, ((Author)attr).Name); } } } } | cs |
[C# 프로그래밍] 14장 파일입출력 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 12장 리플렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 11장 람다식 (0) | 2016.01.11 |
[C# 프로그래밍] 10장 LINQ (0) | 2016.01.11 |
[C# 프로그래밍] 9장 델리게이트와 이벤트 (0) | 2016.01.11 |
리플렉션 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | using System; using System.Reflection; namespace EX12_Reflection { class General { public int exp; public string Name { get; set; } public int Power { get; set; } public int HP { get; set; } public General() { exp = 0; } public General(string name, int power, int hp) : this() { Name = name; Power = power; HP = hp; } public void Print() { Console.WriteLine("장수명 : {0} POW: {1} HP : {2} Exp : {3}", Name, Power, HP, exp); } } class MainClass { public static void Main (string[] args) { Type type = Type.GetType("EX12_Reflection.General"); // Query Class Info Console.WriteLine("***** Field List *****"); FieldInfo[] fList = type.GetFields(); foreach (FieldInfo f in fList) { Console.WriteLine(f); } Console.WriteLine("***** Property List *****"); PropertyInfo[] pList = type.GetProperties (); foreach (PropertyInfo p in pList) { Console.WriteLine(p); } Console.WriteLine("***** Method List *****"); MethodInfo[] mList = type.GetMethods (); foreach (MethodInfo m in mList) { Console.WriteLine(m); } // Generate New Instance Console.WriteLine("***** Generate New Instance *****"); MethodInfo mdInfo = type.GetMethod("Print"); PropertyInfo nameProp = type.GetProperty("Name"); PropertyInfo powerProp = type.GetProperty("Power"); PropertyInfo hpProp = type.GetProperty("HP"); object general = Activator.CreateInstance(type, "관우,", 99, 100); mdInfo.Invoke(general, null); general = Activator.CreateInstance(type); nameProp.SetValue(general,"여포",null); powerProp.SetValue(general, 100, null); hpProp.SetValue(general, 100, null); mdInfo.Invoke(general, null); } } } | cs |
[C# 프로그래밍] 14장 파일입출력 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 13장 애트리뷰트 (0) | 2016.01.11 |
[C# 프로그래밍] 11장 람다식 (0) | 2016.01.11 |
[C# 프로그래밍] 10장 LINQ (0) | 2016.01.11 |
[C# 프로그래밍] 9장 델리게이트와 이벤트 (0) | 2016.01.11 |
람다식 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | using System; using System.Linq; namespace EX10_LamdaExpression { delegate int Operator(int a, int b); delegate void OperatorCB(int a, int b); class MainClass { public static Operator calculate; public static OperatorCB calculateCB; public static void Main (string[] args) { // Lamda Expression calculate = (int a, int b) => a + b; Console.WriteLine ("{0} + {1} = {2}", 83, 34, calculate (83, 34)); calculate = (int a, int b) => a - b; Console.WriteLine ("{0} + {1} = {2}", 83, 34, calculate (83, 34)); calculate = (int a, int b) => a * b; Console.WriteLine ("{0} + {1} = {2}", 83, 34, calculate (83, 34)); calculate = (int a, int b) => a / b; Console.WriteLine ("{0} + {1} = {2}", 83, 34, calculate (83, 34)); // Lamda Expression Statement calculateCB = (int a, int b) => { int result = a % b; Console.WriteLine ("{0} % {1} = {2}", a, b, result); }; calculateCB(83, 34); // Lamda Expression in LINQ int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0, 13, 15 }; int oddNumberCount = numbers.Where (n => n % 2 != 0).Count(); Console.WriteLine (oddNumberCount); } } } | cs |
[C# 프로그래밍] 13장 애트리뷰트 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 12장 리플렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 10장 LINQ (0) | 2016.01.11 |
[C# 프로그래밍] 9장 델리게이트와 이벤트 (0) | 2016.01.11 |
[C# 프로그래밍] 8장 반복기와 양보문 (0) | 2016.01.11 |
LINQ 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; using System.Linq; namespace EX10_LINQ { class General { public string Name { get; set; } public int Power { get; set; } public int HP { get; set; } } class MainClass { public static void Main (string[] args) { General[] generals = { new General() {Name = "유비", Power = 75, HP = 100}, new General() {Name = "관우", Power = 98, HP = 100}, new General() {Name = "장비", Power = 99, HP = 100}, new General() {Name = "간옹", Power = 45, HP = 49}, new General() {Name = "미축", Power = 32, HP = 30} }; var listGenerals = from general in generals where general.HP > 50 orderby general.Power descending select general; foreach (var g in listGenerals) { Console.WriteLine("장수명 : {0} HP : {1}", g.Name, g.HP); } } } } | cs |
[C# 프로그래밍] 12장 리플렉션 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 11장 람다식 (0) | 2016.01.11 |
[C# 프로그래밍] 9장 델리게이트와 이벤트 (0) | 2016.01.11 |
[C# 프로그래밍] 8장 반복기와 양보문 (0) | 2016.01.11 |
[C# 프로그래밍] 7장 인터페이스와 추상클래스 (0) | 2016.01.11 |
델리게이트 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | using System; delegate void Attack(int damage); namespace EX09_Delegate { class Weapon { protected int Damage { get; set; } } class AssultRifle : Weapon { public void Shoot(int damage) { this.Damage = damage; Console.WriteLine ("Shoot Ammo : {0}", Damage); } } class Knife : Weapon { public void Sweep(int damage) { this.Damage = damage; Console.WriteLine ("Sweep Knife : {0}", Damage); } } class Grenade : Weapon { public void Throw(int damage) { this.Damage = damage; Console.WriteLine ("Throw Grenade : {0}", Damage); } } class MainClass { public static void Shoot(int damage) { Console.WriteLine ("Pistol Shoot : {0}", damage); } public static void Main (string[] args) { Attack pistolAttack = new Attack (Shoot); pistolAttack(50); AssultRifle assultRifle = new AssultRifle (); Knife knife = new Knife (); Grenade grenade = new Grenade (); Attack[] playerAttack = { new Attack (assultRifle.Shoot), new Attack (knife.Sweep), new Attack (grenade.Throw) }; playerAttack[0](100); playerAttack[1](200); playerAttack[2](300); Console.WriteLine ("***** Chain Attack *****"); Attack chainAttack = Delegate.Combine (playerAttack [0], playerAttack [0], playerAttack [1], playerAttack [1], playerAttack [2]) as Attack; chainAttack (200); Console.WriteLine ("***** Chain Attack 2*****"); Attack chainAttack2 = new Attack(playerAttack[0]); chainAttack2 += new Attack(playerAttack[1]); chainAttack2 += new Attack(playerAttack[2]); chainAttack2 += new Attack(playerAttack[2]); chainAttack2 += new Attack(playerAttack[0]); chainAttack2 (300); Console.WriteLine ("***** Chain Attack 3*****"); Attack chainAttack3 = new Attack(playerAttack[1]) + new Attack(playerAttack[2]) + new Attack(playerAttack[0]) - new Attack(playerAttack[2]); chainAttack3 (400); } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System; delegate void Operation(int a, int b); namespace EX09_DelegateNoName { class MainClass { public static Operation calculate; public static void Main (string[] args) { calculate = delegate(int a, int b) { Console.WriteLine ("{0} + {1} = {2}", a, b, a + b); }; calculate (83, 34); calculate = delegate(int a, int b) { Console.WriteLine ("{0} - {1} = {2}", a, b, a - b); }; calculate (83, 34); calculate = delegate(int a, int b) { Console.WriteLine ("{0} * {1} = {2}", a, b, a * b); }; calculate (83, 34); calculate = delegate(int a, int b) { Console.WriteLine ("{0} / {1} = {2}", a, b, a / b); }; calculate (83, 34); } } } | cs |
Func 델리게이트 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | using System; namespace EX09_FuncDelegate { class MainClass { class Calculator { public static int Add(int a, int b) { return a + b; } public static int Subtract(int a, int b) { return a - b; } public static int Multiply(int a, int b) { return a * b; } public static int Divide(int a, int b) { return a / b; } } public static void Main (string[] args) { Func<int, int, int> calculate; calculate = Calculator.Add; Console.WriteLine ("{0} + {1} = {2}", 83, 34, calculate (83, 34)); calculate = Calculator.Subtract; Console.WriteLine ("{0} - {1} = {2}", 83, 34, calculate (83, 34)); calculate = Calculator.Multiply; Console.WriteLine ("{0} * {1} = {2}", 83, 34, calculate (83, 34)); calculate = Calculator.Divide; Console.WriteLine ("{0} / {1} = {2}", 83, 34, calculate (83, 34)); } } } | cs |
Action 델리게이트 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | using System; namespace EX09_ActionDelegate { class MainClass { class Calculator { public static void Add(int a, int b) { Console.WriteLine ("{0} + {1} = {2}", a, b, a + b); } public static void Subtract(int a, int b) { Console.WriteLine ("{0} - {1} = {2}", a, b, a - b); } public static void Multiply(int a, int b) { Console.WriteLine ("{0} * {1} = {2}", a, b, a * b); } public static void Divide(int a, int b) { Console.WriteLine ("{0} / {1} = {2}", a, b, a / b); } } public static void Main (string[] args) { Action<int, int> calculate; calculate = Calculator.Add; calculate (83, 34); calculate = Calculator.Subtract; calculate (83, 34); calculate = Calculator.Multiply; calculate (83, 34); calculate = Calculator.Divide; calculate (83, 34); } } } | cs |
이벤트 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; namespace EX09_Event { delegate int Operator(int a, int b); class Calculator { public event Operator operatorCB; public void calculate (int a, int b, string op, Operator opCB) { operatorCB = opCB; Console.WriteLine("{0} {1} {2} = {3}", a, op, b, operatorCB (a, b)); } } class MainClass { public static void Main (string[] args) { Calculator calculator = new Calculator(); calculator.calculate (83, 34, "+", delegate(int a, int b) { return a + b; }); calculator.calculate (83, 34, "-", delegate(int a, int b) { return a - b; }); calculator.calculate (83, 34, "*", delegate(int a, int b) { return a * b; }); calculator.calculate (83, 34, "/", delegate(int a, int b) { return a / b; }); } } } | cs |
[C# 프로그래밍] 11장 람다식 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 10장 LINQ (0) | 2016.01.11 |
[C# 프로그래밍] 8장 반복기와 양보문 (0) | 2016.01.11 |
[C# 프로그래밍] 7장 인터페이스와 추상클래스 (0) | 2016.01.11 |
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
반복기와 양보문 예제 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | using System; namespace EX08_Yield_Enumerator_1 { class MainClass { public static System.Collections.Generic.IEnumerable<int> AddNumber(int n) { int result = 0; for (int i = 0; i <= n; i++) { result += i; yield return result; } } public static void Main (string[] args) { foreach (int i in AddNumber(10)) { Console.WriteLine("{0} ", i); } } } } | cs |
반복기와 양보문 예제 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; namespace EX08_Yield_Enumerator_2 { public class Enemy { public String Name { get; set; } public int HP { get; set; } public int LEVEL { get; set; } } public class EnemyList { public System.Collections.Generic.IEnumerable<Enemy> Next { get { yield return new Enemy { Name = "슬라임", LEVEL = 1, HP = 50 }; yield return new Enemy { Name = "좀비", LEVEL = 2, HP = 100 }; yield return new Enemy { Name = "해골", LEVEL = 2, HP = 150 }; yield return new Enemy { Name = "구울", LEVEL = 3, HP = 220 }; } } } public class MainClass { public static void PrintEnemyList() { var enemys = new EnemyList(); foreach (Enemy enemy in enemys.Next) { Console.WriteLine("LV {0} {1} 의 HP는 {2}", enemy.LEVEL, enemy.Name, enemy.HP); } } static void Main(string[] args) { PrintEnemyList(); } } } | cs |
[C# 프로그래밍] 10장 LINQ (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 9장 델리게이트와 이벤트 (0) | 2016.01.11 |
[C# 프로그래밍] 7장 인터페이스와 추상클래스 (0) | 2016.01.11 |
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
[C# 프로그래밍] 5강 컬렉션 (0) | 2016.01.11 |
인터페이스 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; namespace InterfaceEx { interface IA { void MustBeImplement(string text); } interface IB { string Name { get; set; } } class ClassB : IA, IB { public string Name { get; set; } public void MustBeImplement(string name) { this.Name = name; Console.WriteLine("{0} implement this method!!", this.Name); } } class MainClass { public static void Main (string[] args) { ClassB b = new ClassB(); b.MustBeImplement("B"); //IA iaa = new IA(); IA ia = new ClassB(); ia.MustBeImplement("IA"); Console.ReadKey(); } } } | cs |
추상클래스 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | using System; namespace AbstractClassEx { abstract class ClassA { private string txtA; protected string txtB; public void WriteTextToConsole(string text) { this.txtA = text; Console.WriteLine(this.txtA); } public abstract void MustBeImplemented(string text); } class classB : ClassA { public override void MustBeImplemented(string text) { this.txtB = text; Console.WriteLine("{0} implement this method", this.txtB); } } class MainClass { public static void Main (string[] args) { classB b = new classB(); b.WriteTextToConsole("B"); b.MustBeImplemented("B"); //ClassA aa = new ClassA(); ClassA a = new classB(); a.WriteTextToConsole("A"); a.MustBeImplemented("A"); Console.ReadKey(); } } } | cs |
[C# 프로그래밍] 9장 델리게이트와 이벤트 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 8장 반복기와 양보문 (0) | 2016.01.11 |
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
[C# 프로그래밍] 5강 컬렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 4장 인덱서 (0) | 2016.01.11 |
제네릭 메소드와 클래스 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | using System; namespace GenericEx { class ClassA { public static void CopyArray(int[] src, int[] target) { for (int i = 0; i < src.Length; ++i) { target[i] = src[i]; } } public static void CopyArray(string[] src, string[] target) { for (int i = 0; i < src.Length; ++i) { target[i] = src[i]; } } // 제네릭 메소드 public static void GenericCopyArray<T>(T[] src, T[] target) { for (int i = 0; i < src.Length; ++i) { target[i] = src[i]; } } } // 제네릭 클래스 class GenericClassA<T> { public static void GenericCopyArray(T[] src, T[] target) { for (int i = 0; i < src.Length; ++i) { target[i] = src[i]; } } } class MainClass { public static void Main (string[] args) { int[] iSrc = { 1, 2, 3, 4, 5 }; int[] iTarget = new int[5]; string[] strSrc = { "ab", "cd", "ef", "gh", "ij" }; string[] strTarget = new string[5]; ClassA.CopyArray(iSrc, iTarget); foreach (int i in iTarget) Console.WriteLine(i); ClassA.CopyArray(strSrc, strTarget); foreach (string s in strTarget) Console.WriteLine(s); float[] fSrc = { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f }; float[] fTarget = new float[5]; // 제네릭 메소드의 활용 ClassA.GenericCopyArray<float>(fSrc, fTarget); foreach (float f in fTarget) Console.WriteLine(f); // 제네릭 클래스의 활용 GenericClassA<float>.GenericCopyArray(fSrc, fTarget); foreach (float f in fTarget) Console.WriteLine(f); Console.ReadKey(); } } } | cs |
LinkedList<T> 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | using System; using System.Text; using System.Collections.Generic; namespace LinkedListTEx { class MainClass { private static void Display(LinkedList<string> words, string test) { Console.WriteLine(test); foreach (string word in words) { Console.Write(word + " "); } Console.WriteLine(); Console.WriteLine(); } private static void IndicateNode(LinkedListNode<string> node, string test) { Console.WriteLine(test); if (node.List == null) { Console.WriteLine("Node '{0}' is not in the list.\n", node.Value); return; } StringBuilder result = new StringBuilder("(" + node.Value + ")"); LinkedListNode<string> nodeP = node.Previous; while (nodeP != null) { result.Insert(0, nodeP.Value + " "); nodeP = nodeP.Previous; } node = node.Next; while (node != null) { result.Append(" " + node.Value); node = node.Next; } Console.WriteLine(result); Console.WriteLine(); } public static void Main (string[] args) { string[] words = { "유니티", "C#으로", "스크립팅", "한다"}; // 연결 리스트의 생성 LinkedList<string> sentence = new LinkedList<string>(words); Display(sentence, "연결 리스트의 값은:"); Console.WriteLine("sentence.Contains(\"유니티\") = {0}", sentence.Contains("유니티")); sentence.AddFirst("오늘은"); Display(sentence, "Test 1: 리스트 앞에 '오늘은' 문자열 추가"); LinkedListNode<string> mark1 = sentence.First; sentence.RemoveFirst(); sentence.AddLast(mark1); Display(sentence, "Test 2: 마지막 단어를 끝으로 이동"); sentence.RemoveLast(); sentence.AddLast("오늘만"); Display(sentence, "Test 3: 마지막 단어를 '오늘만' 으로 변경"); mark1 = sentence.Last; sentence.RemoveLast(); sentence.AddFirst(mark1); Display(sentence, "Test 4: 마지막 노드를 첫 노드로 이동"); sentence.RemoveFirst(); LinkedListNode<string> current = sentence.FindLast("C#으로"); IndicateNode(current, "Test 5: '스크립팅'이라는 단어를 찾아 가리킨다 "); sentence.AddAfter(current, "자바스크립트로"); sentence.AddAfter(current, "그리고"); IndicateNode(current, "Test 6: '스크립팅' 단어 뒤에 단어 추가"); current = sentence.Find("유니티"); IndicateNode(current, "Test 7: '유니티' 노드를 가리킨다"); sentence.AddBefore(current, "오늘과"); sentence.AddBefore(current, "내일은"); IndicateNode(current, "Test 8: '오늘과', '내일은' 단어를 '유니티' 노드 앞에 추가"); } } } | cs |
List<T> 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | using System; using System.Collections.Generic; namespace ListTEx { public class Enemy { public string Name { get; set; } public int Level { get; set; } public int HP { get; set; } public int Exp { get; set; } public void printEnemyInfo() { Console.WriteLine ("Name : {0} Level : {1} HP : {2} Exp : {3}", Name, Level, HP, Exp); } } class MainClass { public static List<Enemy> enemyList; public static void Main (string[] args) { enemyList = new List<Enemy>(); // 추가 enemyList.Add (new Enemy () { Name = "Slime", Level = 1, HP = 200, Exp = 30 }); enemyList.Add (new Enemy () { Name = "Zombie", Level = 2, HP = 100, Exp = 50 }); enemyList.Add (new Enemy () { Name = "Skeleton", Level = 3, HP = 120, Exp = 80 }); enemyList.Add (new Enemy () { Name = "Bugbear", Level = 4, HP = 300, Exp = 150 }); // 삽입 enemyList.Insert (2, new Enemy () { Name = "Bugbear", Level = 5, HP = 350, Exp = 180 }); Console.WriteLine ("**********************"); foreach (Enemy enemy in enemyList) { enemy.printEnemyInfo(); } // 삭제 enemyList.RemoveAt (2); // 검색 후 삭제 Enemy bugBear = enemyList.Find (x => x.Name.Equals ("Bugbear")); enemyList.Remove (bugBear); Console.WriteLine ("**********************"); foreach (Enemy enemy in enemyList) { enemy.printEnemyInfo(); } } } } | cs |
Dictionary<TKey, TValue> 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | using System; using System.Collections.Generic; namespace DictionaryTEx { public class FileFormatTable { private Dictionary<string, string> openWith; public FileFormatTable() { openWith = new Dictionary<string, string>(); // 추가 openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); openWith.Add("odf", "wordpad.exe"); // 이미 할당 된 키일 경우 try { openWith.Add("txt", "winword.exe"); } catch { Console.WriteLine("An element with Key = \"txt\" already exists."); } // 제거 openWith.Remove("odf"); } public void printTable() { // 탐색 foreach (KeyValuePair<string, string> d in openWith) Console.WriteLine("Key = {0}, Value = {1}", d.Key, d.Value); } } class MainClass { public static void Main (string[] args) { FileFormatTable fileFormatTable = new FileFormatTable (); fileFormatTable.printTable (); } } } | cs |
Queue<T> 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | using System; using System.Collections.Generic; namespace QueueTEx { public class Enemy { public string Name { get; set; } public int Level { get; set; } public int HP { get; set; } public int Exp { get; set; } public void printEnemyInfo() { Console.WriteLine ("Name : {0} Level : {1} HP : {2} Exp : {3}", Name, Level, HP, Exp); } } class MainClass { public static Queue<Enemy> enemyQueue; public static void Main (string[] args) { enemyQueue = new Queue<Enemy>(); // 추가 enemyQueue.Enqueue (new Enemy () { Name = "Slime", Level = 1, HP = 200, Exp = 30 }); enemyQueue.Enqueue (new Enemy () { Name = "Zombie", Level = 2, HP = 100, Exp = 50 }); enemyQueue.Enqueue (new Enemy () { Name = "Skeleton", Level = 3, HP = 120, Exp = 80 }); enemyQueue.Enqueue (new Enemy () { Name = "Bugbear", Level = 4, HP = 300, Exp = 150 }); enemyQueue.Enqueue (new Enemy () { Name = "Bugbear", Level = 5, HP = 350, Exp = 180 }); Console.WriteLine ("**********************"); foreach (Enemy enemy in enemyQueue) { enemy.printEnemyInfo(); } // 삭제 Console.WriteLine ("********* Out *********"); Enemy outEnemy = enemyQueue.Dequeue (); outEnemy.printEnemyInfo (); Console.WriteLine ("**********************"); foreach (Enemy enemy in enemyQueue) { enemy.printEnemyInfo(); } // 검색 후 삭제 Console.WriteLine ("******** First *********"); Enemy firstEnemy = enemyQueue.Peek(); firstEnemy.printEnemyInfo (); } } } | cs |
Stack<T> 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | using System; using System.Collections.Generic; namespace StackTEx { public class Enemy { public string Name { get; set; } public int Level { get; set; } public int HP { get; set; } public int Exp { get; set; } public void printEnemyInfo() { Console.WriteLine ("Name : {0} Level : {1} HP : {2} Exp : {3}", Name, Level, HP, Exp); } } class MainClass { public static Stack<Enemy> enemyStack; public static void Main (string[] args) { enemyStack = new Stack<Enemy>(); // 추가 enemyStack.Push (new Enemy () { Name = "Slime", Level = 1, HP = 200, Exp = 30 }); enemyStack.Push (new Enemy () { Name = "Zombie", Level = 2, HP = 100, Exp = 50 }); enemyStack.Push (new Enemy () { Name = "Skeleton", Level = 3, HP = 120, Exp = 80 }); enemyStack.Push (new Enemy () { Name = "Bugbear", Level = 4, HP = 300, Exp = 150 }); enemyStack.Push (new Enemy () { Name = "Bugbear", Level = 5, HP = 350, Exp = 180 }); Console.WriteLine ("**********************"); foreach (Enemy enemy in enemyStack) { enemy.printEnemyInfo(); } // 삭제 Console.WriteLine ("********* Out *********"); Enemy outEnemy = enemyStack.Pop (); outEnemy.printEnemyInfo (); Console.WriteLine ("**********************"); foreach (Enemy enemy in enemyStack) { enemy.printEnemyInfo(); } // 검색 후 삭제 Console.WriteLine ("******** Last *********"); Enemy lastEnemy = enemyStack.Peek(); lastEnemy.printEnemyInfo (); } } } | cs |
[C# 프로그래밍] 8장 반복기와 양보문 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 7장 인터페이스와 추상클래스 (0) | 2016.01.11 |
[C# 프로그래밍] 5강 컬렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 4장 인덱서 (0) | 2016.01.11 |
[C# 프로그래밍] 3장 프로퍼티 (0) | 2016.01.11 |
ArrayList 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | using System; using System.Collections; namespace ArrayListEx { public class EnemyArrayList { private ArrayList enemyArray; public EnemyArrayList() { enemyArray = new ArrayList (); // 추가 enemyArray.Add("Zombie"); enemyArray.Add("Skeleton"); enemyArray.Add("Slime"); enemyArray.Add("SlimeX"); // 특정 인덱스에 추가 enemyArray.Insert (2, "KingWolf"); enemyArray.Insert (2, "Wolf"); // 삭제 enemyArray.Remove ("SlimeX"); } public void printEnemys() { // 탐색 foreach (Object enemy in enemyArray) Console.WriteLine (enemy); } } class MainClass { public static void Main (string[] args) { EnemyArrayList enemyArrayList = new EnemyArrayList (); enemyArrayList.printEnemys (); } } } | cs |
Hashtable 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | using System; using System.Collections; namespace HashtableEx { public class FileFormatTable { private Hashtable openWith; public FileFormatTable() { openWith = new Hashtable(); // 추가 openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); openWith.Add("odf", "wordpad.exe"); // 이미 할당 된 키일 경우 try { openWith.Add("txt", "winword.exe"); } catch { Console.WriteLine("An element with Key = \"txt\" already exists."); } // 제거 openWith.Remove("odf"); } public void printTable() { // 탐색 foreach (DictionaryEntry d in openWith) Console.WriteLine("Key = {0}, Value = {1}", d.Key, d.Value); } } class MainClass { public static void Main (string[] args) { FileFormatTable fileFormatTable = new FileFormatTable (); fileFormatTable.printTable (); } } } | cs |
Queue 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | using System; using System.Collections; namespace QueueEx { public class EnemyQueue { private Queue enQueue; public EnemyQueue() { enQueue = new Queue (); // Enqueue enQueue.Enqueue ("Zombie1"); enQueue.Enqueue ("Zombie2"); enQueue.Enqueue ("Skeleton"); enQueue.Enqueue ("Slime"); enQueue.Enqueue ("SlimeX1"); enQueue.Enqueue ("SlimeX2"); // Dequeue Object enemy = enQueue.Dequeue (); Console.WriteLine("Out : {0}", enemy); } public void printEnemys() { // 탐색 foreach (Object enemy in enQueue) Console.WriteLine ("Queue : {0}",enemy); // 현재 맨 앞에 위치한 개체 Console.WriteLine("First Enemy : {0}", enQueue.Peek ()); } } class MainClass { public static void Main (string[] args) { EnemyQueue enemyQueue = new EnemyQueue (); enemyQueue.printEnemys (); } } } | cs |
Stack 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | using System; using System.Collections; namespace StackEx { public class EnemyStack { private Stack enStack; public EnemyStack() { enStack = new Stack (); // Push enStack.Push ("Zombie1"); enStack.Push ("Zombie2"); enStack.Push ("Skeleton"); enStack.Push ("Slime"); enStack.Push ("SlimeX1"); enStack.Push ("SlimeX2"); // Pop Object enemy = enStack.Pop (); Console.WriteLine("Out : {0}", enemy); } public void printEnemys() { // 탐색 foreach (Object enemy in enStack) Console.WriteLine ("Queue : {0}",enemy); // 현재 마지막에 위치한 개체 Console.WriteLine("Last Enemy : {0}", enStack.Peek ()); } } class MainClass { public static void Main (string[] args) { EnemyStack enemyStack = new EnemyStack (); enemyStack.printEnemys (); } } } | cs |
[C# 프로그래밍] 7장 인터페이스와 추상클래스 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
[C# 프로그래밍] 4장 인덱서 (0) | 2016.01.11 |
[C# 프로그래밍] 3장 프로퍼티 (0) | 2016.01.11 |
[C# 프로그래밍] 2장 클래스 (0) | 2016.01.11 |
인덱서 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | using System; namespace IndexerEx { class ClassA { private int[] array; public ClassA() { array = new int[1]; } public int this[int index] { get { return array[index]; } set { if (index >= array.Length) { Array.Resize<int>(ref array, index + 1); Console.WriteLine("Array Resized: {0}", array.Length); } array[index] = value; } } public int Length { get { return array.Length; } } } class MainClass { public static void Main (string[] args) { ClassA a = new ClassA(); for (int i = 0; i < 10; ++i) { a[i] = i; } for (int j = 0; j < a.Length; ++j) { Console.WriteLine(a[j]); } Console.ReadKey(); } } } | cs |
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 5강 컬렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 3장 프로퍼티 (0) | 2016.01.11 |
[C# 프로그래밍] 2장 클래스 (0) | 2016.01.11 |
[C# 프로그래밍] 1장 C# 프로그래밍 기초 (0) | 2016.01.11 |
프로퍼티 사용 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | using System; namespace PropertyEx { class ClassA { //* private int age; private string name; public int GetAge() { return age; } public void SetAge(int age) { this.age = age; } public string GetName() { return name; } public void SetName(string name) { this.name = name; } //*/ // Old Property; public int Age { get { return age; } set { age = value; } } public string Name { get { return name; } set { name = value; } } // Auto Property public int AAge { get; set; } public string AName { get; set; } } class MainClass { public static void Main (string[] args) { ClassA a = new ClassA(); a.SetAge(75); a.SetName("황충"); Console.WriteLine("Age : {0}", a.GetAge()); Console.WriteLine("Name : {0}", a.GetName()); a.Age = 45; a.Name = "관우"; Console.WriteLine("Age : {0}", a.Age); Console.WriteLine("Name : {0}", a.Name); a.AAge = 32; a.AName = "제갈량"; Console.WriteLine("Age : {0}", a.AAge); Console.WriteLine("Name : {0}", a.AName); Console.ReadKey(); } } } | cs |
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 5강 컬렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 4장 인덱서 (0) | 2016.01.11 |
[C# 프로그래밍] 2장 클래스 (0) | 2016.01.11 |
[C# 프로그래밍] 1장 C# 프로그래밍 기초 (0) | 2016.01.11 |
static 필드와 메소드 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | using System; namespace StaticKeywordEx { class ClassA { public static int valueA; public int valueB; public static void printA() { Console.WriteLine ("static 멤버 변수 valueA : {0}", valueA); } public void printB() { Console.WriteLine ("non-static 멤버 변수 valueB : {0}", valueB); } } class MainClass { public static void Main (string[] args) { ClassA.valueA = 123; ClassA.printA (); // static 멤버 함수 호출 ClassA objA = new ClassA (); objA.valueB = 456; objA.printB (); // non-static 멤버 함수 호출 } } } | cs |
this 생성자 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | using System; namespace CSharp_ThisConstructor { class ClassA { string strA; string strB; string strC; public ClassA() { this.strA = "첫 번째 생성자 값은? 없다"; } public ClassA(int b) : this() { this.strB = "두 번째 생성자 값은? " + b.ToString(); } public ClassA(int b, int c) : this(b) { this.strC = "세 번째 생성자 값은? " + b.ToString() + ", " + c.ToString(); } public void printFields() { Console.WriteLine("*******************", strA, strB, strC); Console.WriteLine("{0}\n{1}\n{2}\n", strA, strB, strC); } } class Program { static void Main(string[] args) { ClassA obj1 = new ClassA(); obj1.printFields(); ClassA obj2 = new ClassA(123); obj2.printFields(); ClassA obj3 = new ClassA(45, 678); obj3.printFields(); obj1 = new ClassA(); Console.ReadKey(); } } } | cs |
base 생성자 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using System; namespace BaseConstructorEx { class ClassA { protected string name; public ClassA(string name) { this.name = name; Console.WriteLine ("**************"); Console.WriteLine("클래스A의 이름은 {0} 입니다", this.name); } } class ClassB : ClassA { public ClassB(string name) : base(name) { Console.WriteLine("클래스B의 이름은 {0} 입니다.", this.name); Console.WriteLine ("**************"); } } class Program { static void Main(string[] args) { ClassA a = new ClassA("토끼"); ClassB b = new ClassB("거북이"); Console.ReadKey(); } } } | cs |
클래스 형 변환 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using System; namespace TypeCastingEx { class ClassA { } class ClassB : ClassA { } class MainClass { public static void Main (string[] args) { ClassA objA = new ClassA (); ClassB objB = new ClassB (); ClassA objC = (ClassA)objB; ClassA objD = objB as ClassA; if (objA is ClassB) { Console.WriteLine ("objA == ClassB is true"); } else { Console.WriteLine ("objA == ClassB is false"); } if (objD is ClassA) { Console.WriteLine ("objD == ClassA is true"); } else { Console.WriteLine ("objD == ClassA is false"); } } } } | c |
메소드 오버라이딩 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using System; namespace MethodOverideEx { class ClassA { protected int valueA; public virtual void printValue() { Console.WriteLine ("Class A 수행 값은 : {0}", this.valueA); } } class ClassB : ClassA { public ClassB(int val) { this.valueA = val; } // 재정의 public override void printValue() { Console.WriteLine ("Class B 수행 값은 : {0}", this.valueA); } } class MainClass { public static void Main (string[] args) { ClassB objB = new ClassB (123); objB.printValue (); // 재정의 한 코드 수행 } } } | cs |
중첩 클래스 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | namespace InnerClassEx { public class ClassA { private int valueA; public class InnerClassA { private ClassA parent; public InnerClassA() { } public InnerClassA(ClassA parent) { this.parent = parent; this.parent.valueA = 10; // privite 멤버도 접근 가능 } public void printA() { Console.WriteLine ("클래스A의 값A는 {0}", this.parent.valueA); } } } class MainClass { public static void Main (string[] args) { ClassA obj = new ClassA (); ClassA.InnerClassA innerObj = new ClassA.InnerClassA(obj); innerObj.printA (); } } } | cs |
분할 클래스 예제
FileA.cs
1 2 3 4 5 6 7 8 9 10 11 | using System; namespace PartialClassEx { partial class ClassFile { int valueA; int valueB; int valueC; } } | cs |
FileB.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 | using System; namespace PartialClassEx { partial class ClassFile { public ClassFile () { valueA = 123; valueB = 456; valueC = 789; } } } | cs |
FileC.cs
1 2 3 4 5 6 7 8 9 10 11 12 | using System; namespace PartialClassEx { partial class ClassFile { public void printValues() { Console.WriteLine(valueA); Console.WriteLine(valueB); Console.WriteLine(valueC); } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 | using System; namespace PartialClassEx { class MainClass { public static void Main (string[] args) { ClassFile cf = new ClassFile (); cf.printValues (); } } } | cs |
클래스 객체의 복사 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | using System; namespace ClassCopyEx { class MainClass { class Enemy { public int level; public int exp; public Enemy() {} public Enemy(int level, int exp) { this.level = level; this.exp = exp; } public Enemy DeepCopy() { Enemy objA = new Enemy (this.level, this.exp); return objA; } public void printInfo() { Console.WriteLine ("Level : {0}", this.level); Console.WriteLine ("Exp : {0}", this.exp); } } public static void Main (string[] args) { Enemy objA = new Enemy (); objA.level = 5; objA.exp = 80; // 얕은 복사 Enemy objB = objA; objB.exp = 120; objA.printInfo (); objB.printInfo (); // 깊은 복사 Enemy objC = objA.DeepCopy(); objC.exp = 200; objA.printInfo (); objC.printInfo (); } } } | cs |
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 5강 컬렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 4장 인덱서 (0) | 2016.01.11 |
[C# 프로그래밍] 3장 프로퍼티 (0) | 2016.01.11 |
[C# 프로그래밍] 1장 C# 프로그래밍 기초 (0) | 2016.01.11 |
[C# 프로그래밍] 6강 제네릭 프로그래밍 (0) | 2016.01.11 |
---|---|
[C# 프로그래밍] 5강 컬렉션 (0) | 2016.01.11 |
[C# 프로그래밍] 4장 인덱서 (0) | 2016.01.11 |
[C# 프로그래밍] 3장 프로퍼티 (0) | 2016.01.11 |
[C# 프로그래밍] 2장 클래스 (0) | 2016.01.11 |
예제 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_StrategyPattern { abstract class Strategy { public abstract void AlgorithmInterface(); } class ConcreteStrategyA : Strategy { public override void AlgorithmInterface() { Console.WriteLine( "Called ConcreteStrategyA.AlgorithmInterface()"); } } class ConcreteStrategyB : Strategy { public override void AlgorithmInterface() { Console.WriteLine( "Called ConcreteStrategyB.AlgorithmInterface()"); } } class ConcreteStrategyC : Strategy { public override void AlgorithmInterface() { Console.WriteLine( "Called ConcreteStrategyC.AlgorithmInterface()"); } } class Context { private Strategy _strategy; public Context(Strategy strategy) { this._strategy = strategy; } public void ContextInterface() { _strategy.AlgorithmInterface(); } } class Program { static void Main(string[] args) { Context context; context = new Context(new ConcreteStrategyA()); context.ContextInterface(); context = new Context(new ConcreteStrategyB()); context.ContextInterface(); context = new Context(new ConcreteStrategyC()); context.ContextInterface(); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제16강 옵저버 패턴 (0) | 2015.07.27 |
---|---|
[C# 디자인패턴] 제15강 미디에이터 패턴 (0) | 2015.07.24 |
[C# 디자인패턴] 제14강 이터레이터(반복자) 패턴 (0) | 2015.07.23 |
[C# 디자인패턴] 제13강 커맨드패턴 (0) | 2015.07.22 |
[C# 디자인패턴] 제12강 프록시 패턴 (0) | 2015.07.21 |
예제 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_ObserverPattern { abstract class Observer { public abstract void Update(); } class ConcreteObserver : Observer { private string _name; private string _observerState; private ConcreteSubject _subject; public ConcreteObserver(ConcreteSubject subject, string name) { this._subject = subject; this._name = name; } public override void Update() { _observerState = _subject.SubjectState; Console.WriteLine("Observer {0}'s new state is {1}", _name, _observerState); } public ConcreteSubject Subject { get; set; } } abstract class Subject { private List<Observer> _observers = new List<Observer>(); public void Attach(Observer observer) { _observers.Add(observer); } public void Detach(Observer observer) { _observers.Remove(observer); } public void Notify() { foreach (Observer o in _observers) { o.Update(); } } } class ConcreteSubject : Subject { public string SubjectState { get; set; } } class Program { static void Main(string[] args) { ConcreteSubject s = new ConcreteSubject(); s.Attach(new ConcreteObserver(s, "X")); s.Attach(new ConcreteObserver(s, "Y")); s.Attach(new ConcreteObserver(s, "Z")); s.SubjectState = "ABC"; s.Notify(); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제17강 전략 패턴 (0) | 2015.07.28 |
---|---|
[C# 디자인패턴] 제15강 미디에이터 패턴 (0) | 2015.07.24 |
[C# 디자인패턴] 제14강 이터레이터(반복자) 패턴 (0) | 2015.07.23 |
[C# 디자인패턴] 제13강 커맨드패턴 (0) | 2015.07.22 |
[C# 디자인패턴] 제12강 프록시 패턴 (0) | 2015.07.21 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_MediatorPattern { abstract class Mediator { public abstract void Send(string message, Colleague colleague); } class ConcreteMediator : Mediator { private ConcreteColleague1 _colleague1; private ConcreteColleague2 _colleague2; public ConcreteColleague1 Colleague1 { set { _colleague1 = value; } } public ConcreteColleague2 Colleague2 { set { _colleague2 = value; } } public override void Send(string message, Colleague colleague) { if (colleague == _colleague1) { _colleague2.Notify(message); } else { _colleague1.Notify(message); } } } abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } } class ConcreteColleague1 : Colleague { public ConcreteColleague1(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("Colleague1 gets message: " + message); } } class ConcreteColleague2 : Colleague { public ConcreteColleague2(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("Colleague2 gets message: " + message); } } class Program { static void Main(string[] args) { ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.Colleague1 = c1; m.Colleague2 = c2; c1.Send("How are you?"); c2.Send("Fine, thanks"); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제17강 전략 패턴 (0) | 2015.07.28 |
---|---|
[C# 디자인패턴] 제16강 옵저버 패턴 (0) | 2015.07.27 |
[C# 디자인패턴] 제14강 이터레이터(반복자) 패턴 (0) | 2015.07.23 |
[C# 디자인패턴] 제13강 커맨드패턴 (0) | 2015.07.22 |
[C# 디자인패턴] 제12강 프록시 패턴 (0) | 2015.07.21 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | using System; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_IteratorPattern { abstract class Aggregate { public abstract Iterator CreateIterator(); } class ConcreteAggregate : Aggregate { private ArrayList _items = new ArrayList(); public override Iterator CreateIterator() { return new ConcreteIterator(this); } public int Count { get { return _items.Count; } } public object this[int index] { get { return _items[index]; } set { _items.Insert(index, value); } } } abstract class Iterator { public abstract object First(); public abstract object Next(); public abstract bool IsDone(); public abstract object CurrentItem(); } class ConcreteIterator : Iterator { private ConcreteAggregate _aggregate; private int _current = 0; public ConcreteIterator(ConcreteAggregate aggregate) { this._aggregate = aggregate; } public override object First() { return _aggregate[0]; } public override object Next() { object ret = null; if (_current < _aggregate.Count - 1) { ret = _aggregate[++_current]; } return ret; } public override object CurrentItem() { return _aggregate[_current]; } public override bool IsDone() { return _current >= _aggregate.Count; } } class Program { static void Main(string[] args) { ConcreteAggregate a = new ConcreteAggregate(); a[0] = "Item A"; a[1] = "Item B"; a[2] = "Item C"; a[3] = "Item D"; ConcreteIterator i = new ConcreteIterator(a); Console.WriteLine("Iterating over collection:"); object item = i.First(); while (item != null) { Console.WriteLine(item); item = i.Next(); } Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제16강 옵저버 패턴 (0) | 2015.07.27 |
---|---|
[C# 디자인패턴] 제15강 미디에이터 패턴 (0) | 2015.07.24 |
[C# 디자인패턴] 제13강 커맨드패턴 (0) | 2015.07.22 |
[C# 디자인패턴] 제12강 프록시 패턴 (0) | 2015.07.21 |
[C# 디자인패턴] 제11강 퍼사드 패턴 (0) | 2015.07.20 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | using System; namespace CSharp_CommandPattern { abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } public abstract void Execute(); } class ConcreteCommand : Command { public ConcreteCommand(Receiver receiver) : base(receiver) { } public override void Execute() { receiver.Action(); } } class Receiver { public void Action() { Console.WriteLine("Called Receiver.Action()"); } } class Invoker { private Command _command; public void SetCommand(Command command) { this._command = command; } public void ExecuteCommand() { _command.Execute(); } } class Program { static void Main() { Receiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker(); invoker.SetCommand(command); invoker.ExecuteCommand(); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제15강 미디에이터 패턴 (0) | 2015.07.24 |
---|---|
[C# 디자인패턴] 제14강 이터레이터(반복자) 패턴 (0) | 2015.07.23 |
[C# 디자인패턴] 제12강 프록시 패턴 (0) | 2015.07.21 |
[C# 디자인패턴] 제11강 퍼사드 패턴 (0) | 2015.07.20 |
[C# 디자인패턴] 제10강 데코레이터패턴 (0) | 2015.07.18 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_DesignPattern { abstract class Subject { public abstract void Request(); } class RealSubject : Subject { public override void Request() { Console.WriteLine("Cakked RealSubject.Request"); } } class Proxy : Subject { private RealSubject _realSubject; public override void Request() { if (_realSubject == null) { _realSubject = new RealSubject(); } _realSubject.Request(); } } class Program { static void Main(string[] args) { Proxy proxy = new Proxy(); proxy.Request(); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제14강 이터레이터(반복자) 패턴 (0) | 2015.07.23 |
---|---|
[C# 디자인패턴] 제13강 커맨드패턴 (0) | 2015.07.22 |
[C# 디자인패턴] 제11강 퍼사드 패턴 (0) | 2015.07.20 |
[C# 디자인패턴] 제10강 데코레이터패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제9강 컴포지트 패턴 (0) | 2015.07.18 |
예제코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp_FacedePattern
{
class SubSystemOne {
public void MethodOne() {
Console.WriteLine(" SubSystemOne Method");
}
}
class SubSystemTwo {
public void MethodTwo() {
Console.WriteLine(" SubSystemTwo Method");
}
}
class SubSystemThree {
public void MethodThree() {
Console.WriteLine(" SubSystemThree Method");
}
}
class SubSystemFour {
public void MethodFour() {
Console.WriteLine(" SubSystemFour Method");
}
}
class Facade {
private SubSystemOne _one;
private SubSystemTwo _two;
private SubSystemThree _three;
private SubSystemFour _four;
public Facade() {
_one = new SubSystemOne();
_two = new SubSystemTwo();
_three = new SubSystemThree();
_four = new SubSystemFour();
}
public void MethodA() {
Console.WriteLine("\nMethodA() ---- ");
_one.MethodOne();
_two.MethodTwo();
_four.MethodFour();
}
public void MethodB() {
Console.WriteLine("\nMethodB() ---- ");
_two.MethodTwo();
_three.MethodThree();
}
}
class Program
{
static void Main(string[] args)
{
Facade facade = new Facade();
facade.MethodA();
facade.MethodB();
Console.ReadKey();
}
}
}
|
cs |
[C# 디자인패턴] 제13강 커맨드패턴 (0) | 2015.07.22 |
---|---|
[C# 디자인패턴] 제12강 프록시 패턴 (0) | 2015.07.21 |
[C# 디자인패턴] 제10강 데코레이터패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제9강 컴포지트 패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제8강 브릿지패턴 (0) | 2015.07.18 |
예제 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_DecoratorPattern { abstract class Component { public abstract void Operation(); } class ConcreteComponent : Component { public override void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); } } abstract class Decorator : Component { protected Component component; public void SetComponent(Component component) { this.component = component; } public override void Operation() { if (component != null) { component.Operation(); } } } class ConcreteDecoratorA : Decorator { public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecoratorA.Operation()"); } } class ConcreteDecoratorB : Decorator { public override void Operation() { base.Operation(); AddedBehavior(); Console.WriteLine("ConcreteDecoratorB.Operation()"); } void AddedBehavior() { } } class Program { static void Main(string[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.SetComponent(c); d2.SetComponent(d1); d2.Operation(); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제12강 프록시 패턴 (0) | 2015.07.21 |
---|---|
[C# 디자인패턴] 제11강 퍼사드 패턴 (0) | 2015.07.20 |
[C# 디자인패턴] 제9강 컴포지트 패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제8강 브릿지패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제7강 어댑터패턴 (0) | 2015.07.18 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_CompositePattern { abstract class Component { protected string name; public Component(string name) { this.name = name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void Display(int depth); } class Composite : Component { private List<Component> _children = new List<Component>(); public Composite(string name) : base(name) { } public override void Add(Component component) { _children.Add(component); } public override void Remove(Component component) { _children.Remove(component); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); foreach (Component component in _children) { component.Display(depth + 2); } } } class Leaf : Component { public Leaf(string name) : base(name) { } public override void Add(Component c) { Console.WriteLine("Cannot add to a leaf"); } public override void Remove(Component c) { Console.WriteLine("Cannot remove from a leaf"); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); } } class Program { static void Main(string[] args) { Composite root = new Composite("root"); root.Add(new Leaf("Leaf A")); root.Add(new Leaf("Leaf B")); Composite comp = new Composite("Composite X"); comp.Add(new Leaf("Leaf XA")); comp.Add(new Leaf("Leaf XB")); root.Add(comp); root.Add(new Leaf("Leaf C")); Leaf leaf = new Leaf("Leaf D"); root.Add(leaf); root.Remove(leaf); root.Display(1); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제11강 퍼사드 패턴 (0) | 2015.07.20 |
---|---|
[C# 디자인패턴] 제10강 데코레이터패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제8강 브릿지패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제7강 어댑터패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제6강 프로토타입패턴 (0) | 2015.07.18 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_BridgePattern { class Abstraction { protected Implementor implementor; public Implementor Implementor { set { implementor = value; } } public virtual void Operation() { implementor.Operation(); } } abstract class Implementor { public abstract void Operation(); } class RefinedAbstraction : Abstraction { public override void Operation() { implementor.Operation(); } } class ConcreteImplementorA : Implementor { public override void Operation() { Console.WriteLine("ConcreteImplementorA Operation"); } } class ConcreteImplementorB : Implementor { public override void Operation() { Console.WriteLine("ConcreteImplementorB Operation"); } } class Program { static void Main(string[] args) { Abstraction ab = new RefinedAbstraction(); ab.Implementor = new ConcreteImplementorA(); ab.Operation(); ab.Implementor = new ConcreteImplementorB(); ab.Operation(); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제10강 데코레이터패턴 (0) | 2015.07.18 |
---|---|
[C# 디자인패턴] 제9강 컴포지트 패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제7강 어댑터패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제6강 프로토타입패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제5강 빌더패턴 (0) | 2015.07.18 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_AdapterPattern { class Target { public virtual void Request() { Console.WriteLine("Called Target Request()"); } } class Adapter : Target { private Adaptee _adaptee = new Adaptee(); public override void Request() { _adaptee.SpecificRequest(); } } class Adaptee { public void SpecificRequest() { Console.WriteLine("Called SpecificRequest()"); } } class Program { static void Main() { Target target = new Adapter(); target.Request(); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제9강 컴포지트 패턴 (0) | 2015.07.18 |
---|---|
[C# 디자인패턴] 제8강 브릿지패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제6강 프로토타입패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제5강 빌더패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제4강 추상팩토리패턴 (0) | 2015.07.18 |
예제코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_Prototype { abstract class Prototype { private string _id; public Prototype(string id) { this._id = id; } public string Id { get { return _id; } } public abstract Prototype Clone(); } class ConcretePrototype1 : Prototype { public ConcretePrototype1(string id) : base(id) { } public override Prototype Clone() { return (Prototype)this.MemberwiseClone(); } } class ConcretePrototype2 : Prototype { public ConcretePrototype2(string id) : base(id) { } public override Prototype Clone() { return (Prototype)this.MemberwiseClone(); } } class Program { static void Main() { ConcretePrototype1 p1 = new ConcretePrototype1("I"); ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone(); Console.WriteLine("Cloned: {0}", c1.Id); ConcretePrototype2 p2 = new ConcretePrototype2("II"); ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone(); Console.WriteLine("Cloned: {0}", c2.Id); Console.ReadKey(); } } } | cs |
[C# 디자인패턴] 제8강 브릿지패턴 (0) | 2015.07.18 |
---|---|
[C# 디자인패턴] 제7강 어댑터패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제5강 빌더패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제4강 추상팩토리패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제3강 팩토리메소드패턴 (0) | 2015.07.18 |
예제코드
namespace 대장간시스템
{
class 장비
{
string 가루;
string 정수;
int 공격력;
int 방어력;
public 장비() { }
public void Set가루(string d) { 가루 = d; }
public void Set정수(string s) { 정수 = s; }
}
abstract class 생산슬롯
{
protected 장비 장비객체;
public 생산슬롯() { }
public 장비 Get장비() { return 장비객체; }
public void 장비객체생성() { 장비객체 = new 장비(); }
public abstract void Build가루();
public abstract void Build정수();
public abstract void Build옵션();
}
class 무기생산슬롯 : 생산슬롯
{
public override void Build가루()
{
장비객체.Set가루("붉은 영혼의 가루");
}
public override void Build정수()
{
장비객체.Set정수("못된 보스의 정수");
}
public override void Build옵션()
{
// 장비객체.공격력 = 랜덤생성;
}
}
class 방어구생산슬롯 : 생산슬롯
{
public override void Build가루()
{
장비객체.Set가루("푸른 영혼의 가루");
}
public override void Build정수()
{
장비객체.Set정수("무지센 보스의 정수");
}
public override void Build옵션()
{
// 장비객체.방어력 = 랜덤생성;
}
}
class 대장장이
{
private 생산슬롯 선택된생산슬롯;
public void Set생산슬롯(생산슬롯 slot) { 선택된생산슬롯 = slot; }
public 장비 Get장비() { return 선택된생산슬롯.Get장비(); }
public void Construct장비()
{
선택된생산슬롯.장비객체생성();
선택된생산슬롯.Build가루();
선택된생산슬롯.Build정수();
선택된생산슬롯.Build옵션();
}
}
class Program
{
static void Main(string[] args)
{
대장장이 히드리그 = new 대장장이();
생산슬롯[] 생산슬롯들 =
{
new 무기생산슬롯(),
new 방어구생산슬롯()
};
히드리그.Set생산슬롯(생산슬롯들[0]);
히드리그.Construct장비();
장비 제작한장비 = 히드리그.Get장비();
}
}
}
[C# 디자인패턴] 제7강 어댑터패턴 (0) | 2015.07.18 |
---|---|
[C# 디자인패턴] 제6강 프로토타입패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제4강 추상팩토리패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제3강 팩토리메소드패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제2강 싱글턴패턴 (0) | 2015.07.18 |
예제코드
namespace 스타크래프트II
{
abstract class 유닛1
{
}
class 마린 : 유닛1
{
}
class 바이킹 : 유닛1
{
}
abstract class 유닛2
{
}
class 불곰 : 유닛2
{
}
class 의료선 : 유닛2
{
}
abstract class 건물
{
public abstract 유닛1 유닛생산1();
public abstract 유닛2 유닛생산2();
}
class 병영 : 건물
{
public override 유닛1 유닛생산1()
{
return new 마린();
}
public override 유닛2 유닛생산2()
{
return new 불곰();
}
}
class 우주공항 : 건물
{
public override 유닛1 유닛생산1()
{
return new 바이킹();
}
public override 유닛2 유닛생산2()
{
return new 의료선();
}
}
class Program
{
static void Main(string[] args)
{
}
}
}
[C# 디자인패턴] 제6강 프로토타입패턴 (0) | 2015.07.18 |
---|---|
[C# 디자인패턴] 제5강 빌더패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제3강 팩토리메소드패턴 (0) | 2015.07.18 |
[C# 디자인패턴] 제2강 싱글턴패턴 (0) | 2015.07.18 |
디자인패턴 개론 (0) | 2015.07.18 |