C# Basic Tutorial (Method 2/2)
2022. 1. 11. 00:00ㆍCSharp/Basic
반응형
확장 Method (Extension Method)
: 새 파생 형식을 만들거나 다시 컴파일하거나 원래 형식을 수정하지 않고도 기존 형식에 메서드를 "추가"할 수 있다.
형태
public static class 클래스명
{
public static 리턴타입 WriteLine(this 타입 타입명)
{
....
}
}
c# 에 미리 정의된 Extension methods
위와 같이 OrderBy 에 마우스를 over 해놓으면 (extension).... 이라는 확장 메소드를 사용했다는 표시가 나온다.
정의
/// <summary>
/// string 형태에 WriteLine 이라는 확장 method 를 추가한다.
/// WriteLine 은 return 이 없는 Console.WriteLine 을 활용한 확장 메소드이다.
/// </summary>
public static class StringExtensions
{
public static void WriteLine(this string self)
{
Console.WriteLine(self);
}
}
사용
// string 에 대한 확장메서드 WriteLine 을 통해
// helloWorld 를 console 에 찍어보자
helloWorld.WriteLine();
명명된 인수 및 선택적 인수
명명된 인수
: 인수를 매개 변수 목록 내의 해당 위치가 아닌 해당 이름과 일치시켜 매개 변수에 대한 인수를 지정할 수 있다.
선택적 인수
: 일부 매개 변수에 대한 인수를 생략할 수 있습니다.
// optional parameter message 는 parameter 를 전달하지 않으면 Hello World! 를 기본값으로 가지고 있다.
void HelloWorldNamedAndOptionalParameter(string name, int age, string message="Hello World!")
{
$"Your name is {name}! ur age is {age} and {message} ".WriteLine(); // string interpolation 과 extension method 를 활용하자
}
// 선택적 인수를 생략해서 호출 (message 생략 기본값 호출)
HelloWorldNamedAndOptionalParameter("yogingang", 1);
// 선택적 인수를 변경해서 호출
HelloWorldNamedAndOptionalParameter("yogingang", 1, "안녕하세요");
// 인수를 명명하여 호출 (순서대로 하지 않아도 됨)
HelloWorldNamedAndOptionalParameter(message : "오호 이런 방법이", name:"내이름은 뭐징!", age: 10);
/* 출력
* Your name is yogingang! ur age is 1 and Hello World!
* Your name is yogingang! ur age is 1 and 안녕하세요
* Your name is 내이름은 뭐징!! ur age is 10 and 오호 이런 방법이
*/
관련영상
반응형
'CSharp > Basic' 카테고리의 다른 글
C# Basic Tutorial (Class - 멤버사용법 및 기타등등) (0) | 2022.01.13 |
---|---|
C# Basic Tutorial (Class - 생성자) (0) | 2022.01.12 |
C# Basic Tutorial (Method 1/2) (0) | 2022.01.10 |
C# Basic Tutorial (Arrays) (0) | 2022.01.09 |
C# Basic Tutorial (Loop) (0) | 2022.01.08 |