================================ Outline ====================================
일반화 프로그래밍
예외처리하기
----------------------------------------------------------------------------
교재 p/342 ch. 11 일반화 프로그래밍
일반화 메소드를 사용할 때, 2개 이상의 매개 변수의 형이 동일한 경우가 있다. object형을 boxing/unboxing을 사용하여 처리해주는 것도 가능하지만 형변환 과정에서 많은 부하가 발생하게 된다. 때문에 이와 같은 경우 일반화 일반화 메소드를 사용하여 처리할 수 있다.
ex)
void CopyArray(int [] source, int [] target)
{
for (int I = 0; I < source.Length; I++)
target[i] = source[i];
}
-> void CopyArray( T[] source, T[] target)
{
for (int I = 0; I < source.Length; I++)
target[i] = source[i];
}
교재 p/345, 일반화 메소드 예제,
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace _20150610_CopyingArray { class Program {
static void CopyArray<T>(T[] source, T[] target) { for (int i = 0; i < source.Length; i++) target[i] = source[i]; }
static void Main(string[] args) { int[] source = { 2, 4, 6, 8, 10 }; int[] target = new int[source.Length];
CopyArray<int>(source, target);
foreach(int element in target) Console.WriteLine(element);
string[] source2 = {"하나", "둘", "셋", "넷", "다섯" }; string[] target2 = new string[source2.Length];
CopyArray<string>(source2, target2);
foreach(string element in target2) Console.WriteLine(element);
} } }
|
<T>(형식 매개 변수)는 타입을 일반화하여 사용할 수 있는 곳에 넣고 반복된 코딩을 피할 수 있게 해준다.
형식 매개 변수를 제약할 수도 있다.
제약 조건 | 설명 |
where T: struct | 형식 인수가 값 형식이어야 합니다. Nullable를 제외한 임의의 값 형식을 지정할 수 있습니다. 자세한 내용은 Nullable 형식 사용(C# 프로그래밍 가이드)를 참조하십시오. |
where T : class | 형식 인수가 참조 형식이어야 합니다. 이는 모든 클래스, 인터페이스, 대리자 또는 배열 형식에도 적용됩니다. |
where T : new() | 형식 인수가 매개 변수 없는 공용 생성자를 가지고 있어야 합니다. 다른 제약 조건과 함께 사용하는 경우 new() 제약 조건은 마지막에 지정해야 합니다. |
where T : <기본 클래스 이름> | 형식 인수가 지정된 기본 클래스이거나 지정된 기본 클래스에서 파생되어야 합니다. |
where T : <인터페이스 이름> | 형식 인수가 지정된 인터페이스이거나 지정된 인터페이스를 구현해야 합니다. 여러 인터페이스 제약 조건을 지정할 수 있습니다. 제한하는 인터페이스는 제네릭이 될 수도 있습니다. |
where T : U | T에 대해 지정한 형식 인수가 U에 대해 지정한 인수이거나 이 인수에서 파생되어야 합니다. |
//프로퍼티 get,set에 대한 학습이 필요하다.
교재 p/353 형식 매개 변수 제약시키기 예제,
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace _20150610_constraintsontype { class StructArray<T> where T : struct { public T[] Array { get; set; } public StructArray(int size) { Array = new T[size]; } }
class RefArray<T> where T : class { public T[] Array { get; set; } public RefArray(int size) { Array = new T[size]; } }
class Base { } class Derived : Base { } class BaseArray<U> where U : Base { public U[] Array { get; set; } public BaseArray(int size) { Array = new U[size]; }
public void CopyArray<T>(T[] Source) where T : U { Source.CopyTo(Array, 0); } } class Program { public static T CreateInstance<T>() where T : new() { return new T(); } static void Main(string[] args) { StructArray<int> a = new StructArray<int>(3); a.Array[0] = 0; a.Array[1] = 1; a.Array[2] = 2;
RefArray<StructArray<double>> b = new RefArray<StructArray<double>>(3); b.Array[0] = new StructArray<double>(5); b.Array[1] = new StructArray<double>(10); b.Array[2] = new StructArray<double>(1005);
BaseArray<Base> c = new BaseArray<Base>(3); c.Array[0] = new Base(); c.Array[1] = new Derived(); c.Array[2] = new CreateInstance<Base>();
BaseArray<Derived> d = new BaseArray<Derived>(3); d.Array[0] = new Derived(); d.Array[1] = new CreateInstance<Derived>(); d.Array[2] = new CreateInstance<Derived>();
BaseArray<Derived> e = new BaseArray<Derived>(3); e.CopyArray<Derived>(d.Array);
} } }
|
일반화 컬렉션 또한 형식 매개 변수를 사용한 형태를 띈다.
일반화 컬렉션의 클래스,

교재 368 ch.12 예외 처리하기
//이 장이 끝나면 ch.20 winform으로 가서 실습을 해 본 후 본래 진도로 복귀한다.
런타임 시 예상외의 결과가 발생했을 경우 운영체제 및 프로그램에서 에러가 나는 것을 방지하고 이 때 사용자가 정의한 임의의 처리가 진행되도록 하는 것을 예외처리라고 한다.
문법은 다음과 같다.

//로직의 최소 단위가 스레드이다.
예외처리하기 예제들,
[9.예외처리 (Exception Handling)예제 \ tryCatch.cs]
using System;
public class MainApp { public static void Main() { try { int zero = 0; int j = 3/zero; // 예외 발생! } catch(Exception e) { Console.WriteLine("예외 발생 : {0}", e.Message); } } }
[9.예외처리 (Exception Handling)예제 \ finally.cs] using System;
public class MainApp { public static void Main() { try { Console.WriteLine("여기는 try 블록 시작"); int zero = 0; int j = 3/zero; // 예외 발생! Console.WriteLine("여기는 try 블록 끝"); } catch(Exception e) { Console.WriteLine("예외 발생 : {0}", e.Message); } finally { Console.WriteLine("여기는 finally 블록"); } } }
[9.예외처리 (Exception Handling)예제 \ Exception.cs] using System;
class Division { public void Divide() { try { int zero = 0; int j = 3/zero; // 예외 발생! } catch(Exception e) { Console.WriteLine("예외 발생 : {0}", e.Message); Console.WriteLine("예외가 발생한 위치 : {0}", e.StackTrace); Console.WriteLine("예외의 종류 : {0}", e.GetType()); Console.WriteLine("에러를 일으킨 객체 : {0}", e.Source); Console.WriteLine("InnerException : {0}", e.InnerException); Console.WriteLine("TargetSite : {0}", e.TargetSite); } } }
public class MainApp { public static void Main() { Division D = new Division(); D.Divide(); } }
[9.예외처리 (Exception Handling)예제 \ MultiException.cs] using System;
class MainApp { public static void Main() { Console.WriteLine("어느 예외를 발생시키겠습니까?"); Console.WriteLine("(1)IndexOutOfRangeException "); Console.WriteLine("(2)Exception"); string s = Console.ReadLine();
if(s == "1") raiseErr(1); else raiseErr(2); }
public static void raiseErr(int n) { try { if (n == 1) { int[] j = new int[1]; j[3] = 2; } else throw(new Exception()); } catch(IndexOutOfRangeException e) { Console.WriteLine("{0} 이 예외를 잡았습니다.", e.GetType()); } catch(Exception e) { Console.WriteLine("{0} 이 예외를 잡았습니다.", e.GetType()); } } }
[9.예외처리 (Exception Handling)예제 \ throw.cs] using System;
public class MainApp { public static void Main() { try { rethrow(); } catch(Exception e) { Console.WriteLine("여기는 Main() 입니다."); Console.WriteLine(e.Message); Console.WriteLine("예외가 발생한 곳은 {0} 입니다.", e.Source); } }
public static void rethrow() { int one = 0;
try { if(one == 0) throw(new Exception("one은 0이 아니라 1입니다.") ); } catch(Exception e) { Console.WriteLine("여기는 rethrow()입니다."); Console.WriteLine(e.Message); Console.WriteLine("예외가 발생한 곳은 {0} 입니다.", e.Source); throw; //예외 처리를 마친 후 다시 예외를 던집니다. } } }
[9.예외처리 (Exception Handling)예제 \ throw2.cs] using System;
class Division { public void Divide() { try { int zero = 0; int j = 3/zero; // 예외 발생! } catch(Exception e) { Console.WriteLine("예외 발생 : {0}", e.Message); Console.WriteLine("예외가 발생한 위치 : {0}", e.StackTrace); Console.WriteLine("예외의 종류 : {0}", e.GetType()); Console.WriteLine("에러를 일으킨 객체 : {0}", e.Source); Console.WriteLine("InnerException : {0}", e.InnerException); Console.WriteLine("TargetSite : {0}", e.TargetSite); } } }
public class MainApp { public static void Main() { Division D = new Division(); try { D.Divide(0); } catch(Exception e) { } }
|