티스토리 뷰

Code/C#

[C#] Extension Methods 샘플 코드

Hide Code 2007. 12. 2. 11:46
아래는 Extension Methods 예제이다.

LINE A는 Extension Methods를 사용했고, LINE B는 Static Method를 사용했다.

둘의 선언 방법과 사용 방법을 비교해보자.

Extension methods are static methods.
Extension methods can only be declared in static classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "9";

int i = s.ToInt32Ext(); // LINE A
Console.WriteLine(i);

int j = EMClass.ToInt32Static(s); // LINE B
Console.WriteLine(j);
}
}

static class EMClass
{
public static int ToInt32Ext(this string s)
{
return Int32.Parse(s);
}

public static int ToInt32Static(string s)
{
return Int32.Parse(s);
}
}
}

'Code > C#' 카테고리의 다른 글

[C#] Thread 샘플 코드 2  (0) 2007.12.07
[C#] Thread 샘플 코드 1  (0) 2007.12.07
[C#] 중복되지 않는 난수 발생 샘플 코드  (0) 2007.11.29
[C#] Jagged Array 선언 방법  (0) 2007.11.29
[C#] 3차원 Array 샘플 코드  (0) 2007.11.29
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/09   »
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
글 보관함