C# 8에서 추가된 기본 인터페이스 메서드은 일반적인 활용도가 딱히 떠오르지 않는데요, 다음의 글을 댓글을 통해
기본 인터페이스 메서드를 사용해서 구현체의 구현 없이 동작하도록 만들 수 있고
이후 구현체에서 이 인터페이스를 구현해서 성능을 좀 더 올릴 수 있는 시나리오입니다.
using System.Collections;
var e = new Enum();
Test1(e);
static void Test1<T>(IEnum<T> enums)
{
Console.WriteLine($"Count: {enums.NewCount()}");
foreach (var n in enums)
Console.WriteLine(n);
}
interface IEnum<T> : IEnumerable<T>
{
int NewCount()
{
var count = 0;
foreach (var i in this)
count++;
return count;
}
}
class Enum : IEnum<int>
{
private readonly List<int> _list = new() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// int IEnum<int>.NewCount() => _list.Count;
public IEnumerator<int> GetEnumerator() => _list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator();
}
| 결과
Count: 10
1
2
3
4
5
6
7
8
9
10
기본 인터페이스 구현체에 의해 Count()
가 구현되어 바로 사용할 수 있습니다.
이후에 주석 처리된 int IEnum<int>.NewCount() => _list.Count;
를 구현함으로써 동일한 결과를 좀 더 나은 성능으로 처리할 수 있게 되는데요,
이런 대표적인 예가 LINQ
가 되는 것입니다.