레이블이 확장메서드인 게시물을 표시합니다. 모든 게시물 표시
레이블이 확장메서드인 게시물을 표시합니다. 모든 게시물 표시

2019/01/06

interface 확장


확장 메서드는 static 메서드를 instance 메서드처럼 호출 할 수 있도록 해준다.

public static class ExtensionMethodSample
{
    public static double Round(this double value)
    {
        return Math.Round(value);
    }
}

//test
double value = 1.7;
Console.WriteLine(value.Round());
//static 메시드와 같은 식으로도 호출 가능하다.
Console.WriteLine(ExtensionMethodSample.Round(value));

interface 를 확장하면 확장된 interface를 구현하는 클래스들은 부모 클래스의 정의된 메서드처럼 사용가능하다.

인터페이스 확장:
public interface IName
{
    string FirstName { get; }
    string LastName { get; }
}

public static class NameExtensions
{
    public static string FullName(this IName name)
    {
        return $"{name.FirstName} {name.LastName}";
    }
}

확장된 인터페이스 사용:
public class Member : IName
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

public class Worker : IName
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

결과 테스트:
//test
Member member = new Member
{
    FirstName = "Member",
    LastName = "Lee"
};

Console.WriteLine(member.FullName());

Worker worker = new Worker
{
    FirstName = "Worker",
    LastName = "Lee"
};

Console.WriteLine(worker.FullName());

실제 Member 와 Worker 에는 FullName() 메서드는 없다.

interface 확장으로 class 수정 없이 기능을 확장 할 수 있다.

2017/11/28

C# yield return, 확장 메서드를 이용하여 Enumerable.Where 만들기

Enumerable.Where 와 같은 동작을 하는 Where2 를 만들어 보자.

public static class EnumerableEx
{
    public static IEnumerable<TSource> Where2<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        foreach (var item in source)
        {
            if (predicate(item))
                yield return item;
        }
    }
}

확장 메서드로 만들어서 IEnumerable.Where2 로 사용 가능하며
yield return 으로 지연 반환을 한다.


List<int> list = new List<int>();

list.Add(1);
list.Add(2);
list.Add(3);

var result = list.Where2(i => i > 1);

foreach (var item in result) { }//result 2, 3

list.Add(4);

foreach (var item in result) { }//result 2, 3, 4

C# 문자열 포함 여부 확인하기.

ToUpper() 를 사용하면 불필요한 문자열을 생성하므로 좋은 방법은 아니다. string text = "This is an apple." ; string apple = "Apple." ; bool ...