확장 메소드는 확장 유형의 인스턴스 메소드인 것처럼 호출되는 정적 메소드입니다. 확장 메서드를 사용하면 새 파생 형식을 만들거나 원래 형식을 다시 컴파일하거나 수정하지 않고도 기존 형식에 메서드를 추가할 수 있습니다.
다음은 우리가 만든 확장 메서드입니다.
public static int myExtensionMethod(this string str) {
return Int32.Parse(str);
} 확장 방법을 사용한 예를 살펴보겠습니다.
예
using System;
using System.Text;
namespace Program {
public static class Demo {
public static int myExtensionMethod(this string str) {
return Int32.Parse(str);
}
}
class Program {
static void Main(string[] args) {
string str1 = "565";
int n = str1.myExtensionMethod();
Console.WriteLine("Result: {0}", n);
Console.ReadLine();
}
}
} 출력
Result: 565