public class MySequence<T>(IEnumerable<T> sequence) : IEnumerable<T>
{
// 묵시적 변환을 위한 요구 조건.
public MySequence<T> Create(IEnumerable<T> sequence) =>
new (sequence);
public MySequence(params T[] elements) : this((IEnumerable<T>)elements) { }
public IEnumerator<T> GetEnumerator() =>
sequence.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
}
Any type that supports a collection initializer, such as System.Collections.Generic.List<T>. Usually, this requirement means the type supports System.Collections.Generic.IEnumerable<T> and there's an accessible Add method to add items to the collection. There must be an implicit conversion from the collection expression elements' type to the collection's element type. For spread elements, there must be an implicit conversion from the spread element's type to the collection's element type.
위의 문장을 간단하게 정리하면 이렇습니다.
대괄호를 이용한 초기화 식은 배열뿐만 아니라, Span(ReadOnlySpan)과 (C# 3.0의) Collection Initializer를 지원하는 타입 및 C# 6.0의 확장 메서드로 Add를 지원하는 IEnumerable 타입에 적용할 수 있습니다.
저도 대충 봤군요. 컴파일이 된다고 하는 말에 꽂혀서 MySequence 타입에 Add도 구현된 줄 알고 그렇게 답변한 것이었습니다.
그런데, 이상하군요. 처음 질문에 했던 예제로는 분명히 Add가 없다면서 컴파일 오류가 발생할 텐데요. 그러니까, 아래의 예제 코드로 해보면,
using System.Collections;
namespace ConsoleApp1;
internal class Program
{
static void Main(string[] args)
{
MySequence<int> mine = [1, 2, 3];
}
}
public class MySequence<T>(IEnumerable<T> sequence) : IEnumerable<T>
{
// 묵시적 변환을 위한 요구 조건.
public MySequence<T> Create(IEnumerable<T> sequence) =>
new(sequence);
public MySequence(params T[] elements) : this((IEnumerable<T>)elements) { }
public IEnumerator<T> GetEnumerator() =>
sequence.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
}
다음과 같이 컴파일 오류가 발생합니다.
error CS1061: ‘MySequence’ does not contain a definition for ‘Add’ and no accessible extension method ‘Add’ accepting a first argument of type ‘MySequence’ could be found (are you missing a using directive or an assembly reference?)