개발팁2016. 7. 19. 11:14

Extention Method C# 3.0 에서 추가된 기능이다.

 

Extention Method 를 정의하는 방법은

 

1. System.Linq 를 사용하겠다고 선언한다.
2. static 클래스와 static 메서드로 정의해야 한다.
3. 첫번째 파라미터에 this 라는 키워드를 사용한다.


 

using System.Linq;

namespace test
{
 public static class Extention
 {
  public static string ToUpperCase(this string value)
  {
   // to do...

   return outString;
  }
  public static string AddString(this string value, string extraValue)
  {
   // to do...

   return outString;
  }
 }
}

 

사용방법

 

string str1 = "abcd efgh";
string str2 = "001002003";

 

// 기존 메서드 호출방법
string outStr1 = Extention.ToUpperCase(str1);
string outStr2 = Extention.AddString(str1, str2);

 

// 확장 메서드 호출방법
string extStr1 = str1.ToUpperCase();
string extStr2 = str1.AddString(str2);

 

 

기존 메서드 호출방법과 확장 메서드 호출방법을 모두 다 사용 가능하다.

 

 

 

 

확장메서드는 Visual Studio 에서 보면, 멤버 메서드와 동일하게 보여지고, 사용된다.

다른점은 오른쪽에 (확장) 이라고 표시가 된다.

 

 

 

배열에서의 확장메서드

 

// 정의

public static int[] OrderByAscending(this int[] n)
{
    // to do...
    return outN;
}

 

// 사용시

int[] nList = { 6, 7, 2, 7, 4, 9, 10, 11, 1 };
nList.OrderByAscending();
 

 

 

IEnumerable Generic 에도 이용할 수 있다.

 

// 정의

public static IEnumerable<T> GetOddData<T>(this IEnumerable<T> data)
{
    int n = 1;
    foreach (T Element in data)
    {
 if ((n++ % 2) == 0)
     yield return Element;
    }
}

 

// 사용

List<int> nList = new List<int>() { 1,2,3,4,5,6,7,8,9,10 };
Dictionary<int, string> Dic = new Dictionary<int, string>() { { 1, "one" }, { 2, "two" }, { 3, "three" }, { 4, "four" }, { 5, "five" }, { 6, "six" } };

 

foreach (int val in nList.GetOddData())
{
 Console.WriteLine(val);
}

 

foreach (var kvValue in Dic.GetOddData())
{
 Console.WriteLine(kvValue.Key + " " + kvValue.Value);
}

 

 

이와같이 홀수번째 데이터만 모아서
IEnumerable 로 리턴하는 Extention Method 를 정의하고,


IEnumerable 에서 상속받은 List 와 Dictionary 객체에
GetOddData 메서드를 그대로 사용하는 방법이다.

Posted by 헝개