Share via


컴파일러 오류 CS1954

업데이트: 2007년 11월

오류 메시지

컬렉션 이니셜라이저에 대해 'method'에 가장 일치하는 오버로드된 메서드를 사용할 수 없습니다. 컬렉션 이니셜라이저 'Add' 메서드에는 ref 또는 out 매개 변수를 사용할 수 없습니다.
The best overloaded method match 'method' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.

컬렉션 이니셜라이저를 사용하여 컬렉션 클래스를 초기화하려면 클래스의 publicAdd 메서드에 ref 또는 out 매개 변수를 사용하지 않아야 합니다.

이 오류를 해결하려면

  • 컬렉션 클래스의 소스 코드를 수정할 수 있는 경우 ref 또는 out 매개 변수를 사용하지 않는 Add 메서드를 사용합니다.

  • 컬렉션 클래스를 수정할 수 없는 경우 기본적으로 제공되는 생성자를 사용하여 클래스를 초기화합니다. 이 경우에는 컬렉션 이니셜라이저를 사용할 수 없습니다.

예제

다음 코드에서는 MyList의 Add 목록에서 유일하게 사용할 수 있는 오버로드에 ref 매개 변수가 있기 때문에 CS1954 오류가 발생합니다.

// cs1954.cs
using System.Collections.Generic;
class MyList<T> : IEnumerable<T>
{
    List<T> _list;
    public void Add(ref T item)
    {
        _list.Add(item);
    }

    public System.Collections.Generic.IEnumerator<T> GetEnumerator()
    {
        int index = 0;
        T current = _list[index];
        while (current != null)
        {
            yield return _list[index++];
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

public class MyClass
{
    public string tree { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        MyList<MyClass> myList = new MyList<MyClass> { new MyClass { tree = "maple" } }; // CS1954
    }
}

참고 항목

참조

개체 및 컬렉션 이니셜라이저(C# 프로그래밍 가이드)