방프리

21.03.31 Chapter3. 제네릭 활용 (Item 28) 본문

C#/Effective C#

21.03.31 Chapter3. 제네릭 활용 (Item 28)

방프리 2021. 3. 31. 14:24

Item 28 : 확장 메서드를 이용하여 구체화된 제네릭 타입을 개선하라

 

기존에 사용 중인 컬렉션 타입에 영향을 주지 않으면서 새로운 기능을 추가하고 싶다면 구체화된 컬렉션

타입에 대해 확장 메서드를 작성하면 된다.

public static class Enumerable
{
    public static int Average(this IEnumerable<int> sequence);
    public static int Max(this IEnumerable<int> sequence);
    public static int Min(this IEnumerable<int> sequence);
    public static int Sum(this IEnumerable<int> sequence);
}

확장 메서드를 사용하지 않는다면 새로운 타입을 추가해야하기 때문에 되도록이면 확장 메서드를 사용하는 것이 좋다.

public class CustomerList : List<Customer>
{
    public void SendEmailCoupons(Coupon sepcialOffer);
    public static IEnumerable<Customer> LostProspects();
}

다음과 같이 구현하게 되면 List<Customer>에 제약을 두어버리기 때문에 Iterator 메서드들을 사용하지 못한다.

확장 메서드를 사용하게되면 쿼리문을 사용할 때에도 굉장히 유용하다.

public static IEnumerable<Customer> LostProspects(
	IEnumerable<Customer> targetList)
{
    IEnumerable<Customer> answer = 
    	from c in targetList
        where DateTime.Now - c.LastOrderDate > TimeSpan.FromDays(30)
        select c;
        
     return answer;
}

 

Comments