C# 8에서 접속의 메서드와 속성을 구현

C# 8에서 접속의 메서드와 속성을 구현

이철우

2019년 9월 C# 8.0이 발표되며[참고 1], 접속에서 메서드와 속성을 '구현’할 수 있게 되었습니다. 한층 더 코드 중복을 피할 수 있게 된 것입니다.

간단한 예로 그 쓰임을 알아봅시다. 아래 코드는 C# 9.0에서 동작합니다.

public interface IBorn
{
    DateOnly Birthday { get; }
    int GetAge(DateOnly date)
    {
        return date.Year - Birthday.Year + 1;
    }
}

public interface IName
{
    string LastName { get; }
    string FirstName { get; }
    string FullName => $"{LastName} {FirstName}";
}
public class Person : IBorn
{
    public Person(DateOnly date)
    {
        Birthday = date;
    }

    public DateOnly Birthday { get; }
}

public class HumanName : IName
{
    public HumanName(string lastName, string firstName)
    {
        LastName = lastName;
        FirstName = firstName;
    }
    public string LastName { get; }
    public string FirstName { get; }

    public override string ToString() => (this as IName).FullName;
}

아래는 시험 코드입니다.

Console.WriteLine("Hello, World!");

var person = new Person(new DateOnly(2000, 1, 1));
Console.WriteLine($"Age: {(person as IBorn).GetAge(DateOnly.FromDateTime(DateTime.Now))}");

var humanName = new HumanName("홍", "길동");
Console.WriteLine($"{humanName} {(humanName as IName).FullName}");

Console.WriteLine("Bye.");

[참고 1] Explicit implementation in interfaces

1개의 좋아요

mixin!!

3개의 좋아요

좋은 글이 있습니다.

Tutorial: Mix functionality in when creating classes using interfaces with default interface methods

1개의 좋아요