출저 및 참고 : http://blog.eairship.kr/144 (누구나가 다 이해할 수 있는 프로그래밍 첫걸음 블로그)
를 보면서 공부하고, 나중에 다시 보기 편하게 여기에 정리해 놓은 것입니다. 원본은 위 글입니다~!
확장 메소드(Extension Method)
- 선언 형식
1 2 3 4 5 6 7 8 9 10 | namespace 네임스페이스명 { public static class 클래스명 { public static 반환형식 메소드명(this 확장대상형식 식별자, 매개변수..) { .. } } } | 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 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Extension; namespace Extension { public static class ExtensionMethod { public static int Multiplication(this int var, int a, int b) { int result = var; for(int i = 0; i < b; i++) result *= a; return result; } } } namespace ConsoleApplication21 { class Program { static void Main(string[] args) { Console.WriteLine("{0}", 5.Multiplication(2, 3)); } } } | cs |
결과 : 40
분할 클래스(Partial Class)
- 클래스의 구현이 길어질 경우, 관리의 편의를 위해 두 개 이상의 소스파일로 분할하여 작업을 수행하는 경우
- partial 키워드를 사용
- 컴파일 시 컴파일러에 의해 하나로 합쳐집니다.
- 사용 예제
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; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication21 { partial class Nested { public void Test() { Console.WriteLine("Test()"); } } partial class Nested { public void Test2() { Console.WriteLine("Test2()"); } } partial class Nested { public void Test3() { Console.WriteLine("Test3()"); } } class Program { static void Main(string[] args) { Nested nested = new Nested(); nested.Test(); nested.Test2(); nested.Test3(); } } } | cs |
결과 : Test()
Test2()
Test3()
중첩 클래스(Nested Class)
- 클래스 내에 클래스가 정의된 것.
- 주로 외곽 클래스에서만 사용하고자 할 때, 외부에 정의하는 것보다
관련있는 클래스를 내부 클래스로 두어 코드를 쉽게 이해하기 위해 사용.
- 내부에 쓰인 클래스의 제한자가 명시되어있지 않으면 private로 지정됨.
- 사용 예제
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 ConsoleApplication21 { public class OuterClass { private int a = 70; public class InnerClass { OuterClass instance; public InnerClass(OuterClass a_instance) { instance = a_instance; } public void AccessVariable(int num) { this.instance.a = num; } public void ShowVariable() { Console.WriteLine("a : {0}", this.instance.a); } } } class Program { static void Main(string[] args) { OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = new OuterClass.InnerClass(outer); inner.ShowVariable(); inner.AccessVariable(60); inner.ShowVariable(); } } } | cs |
결과 : a : 70
a : 60
'NOTE > Programming' 카테고리의 다른 글
[C#] 예외처리 (0) | 2018.04.01 |
---|---|
[C#] 인터페이스 (0) | 2018.04.01 |
[C#] 클래스의 상속 (0) | 2018.04.01 |
[C#] Delegate && Event (0) | 2018.04.01 |
[C#] Dictionary<Tkey, TValue> 클래스 (0) | 2018.04.01 |