Extension Methods 사용법은 2가지이다.
기존의 static method 사용법과 동일하게 쓰는 방법도 가능하다.
아래 예제는 exception 발생없이 잘 실행된다.
Extension methods are static methods.
Extension methods can only be declared in static classes.
기존의 static method 사용법과 동일하게 쓰는 방법도 가능하다.
아래 예제는 exception 발생없이 잘 실행된다.
Extension methods are static methods.
Extension methods can only be declared in static classes.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "123";
int i = s.ToInt32();
int j = Extensions.ToInt32(s);
Console.WriteLine(i);
Console.WriteLine(j);
}
}
static class Extensions
{
public static int ToInt32(this string s)
{
return Int32.Parse(s);
}
}
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "123";
int i = s.ToInt32();
int j = Extensions.ToInt32(s);
Console.WriteLine(i);
Console.WriteLine(j);
}
}
static class Extensions
{
public static int ToInt32(this string s)
{
return Int32.Parse(s);
}
}
}
'Code > C#' 카테고리의 다른 글
| [C#] 간단한 Lambda Expression 샘플 코드 (0) | 2008.02.11 |
|---|---|
| [C#] Lambda Expression vs Anonymous Method (0) | 2008.02.11 |
| [C#] const vs readonly (0) | 2008.02.11 |
| PInvoke SetForegroundWindow Sample Code (0) | 2008.01.14 |
| Process Class Sample Code 1 (0) | 2008.01.14 |