티스토리 뷰

Code/C#

[C#] Extension Methods 사용법

Hide Code 2008. 2. 11. 14:45
Extension Methods 사용법은 2가지이다.

기존의 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);
       }
   }
}

'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
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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
글 보관함