-
[C#] 확장 메소드(this)Programming/C# 2020. 10. 11. 23:20
확장 메소드
미리 정의된 형식에 원래 형식을 수정하지 않고도 새로운 메소드를 추가시킬 수 있는 기능이다.
정적 클래스에 정적 메소드일 때만 사용이 가능하다.
정적 메소드의 매개변수에 this [형식] [형식 이름] 형태로 기능을 사용할 수 있다.
예시로 기본적인 학생 정보를 담고 있는 클래스를 만들었다.
클래스 안에는 학생에 대한 이름, 학년, 번호를 담고 있다.
그런 정보들을 SetStudent 메소드의 매개변수를 통해서 정보를 지정해 줄 수 있도록 해줬다.
public class Student { public string m_strName; public byte m_Grade; public byte m_ID; public void SetStudent(string strName, byte Grade, byte ID) { m_strName = strName; m_Grade = Grade; m_ID = ID; } public override string ToString() { return $"Name : {m_strName}, Grade : {m_Grade}, ID : {m_ID}"; } }
Main 함수에서는 Student 인스턴스를 만들어주고 SetStudent 메소드를 통해 값들을 지정해 주었다.
그리고 오버라이드된 ToString()을 통해서 인스턴스에 들어있는 정보를 출력해봤다.
using System; class Program { static void Main(string[] args) { Student student = new Student(); student.SetStudent("HyeonJae", 2, 6); Console.WriteLine(student.ToString()); } }
- 출력 결과 :
이제 확장 메소드를 추가해보자
여기서 중요한 것은 class와 Method 모두 정적(static)으로 지정해 줘야 한다.
public static class StudentExtension { public static void SetStudentName(this Student student, string name) { student.m_strName = name; } public static void SetStudentGrade(this Student student, byte grade) { student.m_Grade = grade; } public static void SetStudentID(this Student student, byte id) { student.m_ID = id; } }
추가해주고 나서 만들어놨던 Student 인스턴스에 접근해보면 SetStudent 메소드 이외에도 SetStudentName, SetStudentGrade, SetStudentID 메소드가 추가된 것을 볼 수 있다.
추가 전 :
추가 후 :
- 확장 메소드 추가
using System; class Program { static void Main(string[] args) { Student student = new Student(); student.SetStudent("HyeonJae", 2, 6); student.SetStudentName("HyeonJae - Park"); // <- 확장 메소드 Console.WriteLine(student.ToString()); } }
- 결과
다음과 같이 적용이 잘 된 것을 볼 수 있다.
'Programming > C#' 카테고리의 다른 글
[C#] Enum 변수를 추가 정의하여 사용하는 방법 (0) 2021.07.06 [C#] Array, List, Dictionary 컬렉션 정리 겸 복습 (2) 2021.01.30 C# 자료형 정리 (0) 2020.02.17