CS1954 de erro do compilador

Mensagem de erro

O melhor método sobrecarregado correspondência 'method' para o elemento inicializador de coleção não pode ser usado.Métodos de 'Adicionar' de inicializador de coleção não podem ter ref ou out parâmetros.

For a collection class to be initialized by using a collection initializer, the class must have a publicAdd method that is not a ref or out parameter.

Para corrigir este erro

  • Se você pode modificar o código-fonte da classe da coleção, fornecer um Add método não terá um ref ou out parâmetro.

  • Se você não pode modificar a classe de coleção, inicializá-lo com os construtores fornece.Não é possível usar um inicializador de coleta com ele.

Exemplo

O exemplo a seguir produz CS1954 porque a sobrecarga do só está disponívelAdd lista no MyList tem um ref parâmetro.

// 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
    }
}

Consulte também

Referência

Objeto e inicializadores de coleção (Guia de programação C#)